Java learning to_String (), equals ()
-
to_String:
-
Returns a string
-
Any class inherits the Object class by default, and the toString () method is inside the Object
-
ToString () can be rewritten
-
class A
{
}
class TestA
{
public static void main(String[] args)
{
A aa = new A();
System.out.printf("%s \n", aa.toString());
//打印出的结果是 A@de3ca2f,A是类名,后面6/8个是类对象地址的16进制 P58讲
//若改为("%s \n", aa); 输出结果一样
}
}
-
equals:
-
equals () is also in class Object
-
So all classes can call equals
-
It is used to determine whether the memory addresses of the two objects are the same, and the return value is true / false
-
class A
{
public A(int i)
{
this.i = i;
}
}
class Testequals
{
public static void main(String[] args)
{
A a1 = new A(2);
A a2 = new A(2);
System.out.println( a1.equals(a2));//判断a1 a2内存地址是否相同
//虽然两个对象所指堆中保存的值一样,但是地址不同
// 会返回 false
}
}
- How to rewrite equals ():
The purpose of rewriting equals is to make two comparisons the same, that is, return true
Rewritten as follows:
class A
{
public int i;
public A(int i)
{
this.i = i;
}
public boolean equals(Object obj) //一定要有public
{
//因为上面传入的参数a2本身已是子类对象,
//所以这里不用写 Obj aa == new A();
A aa = (A)obj; //将父类对象obj(此时obj是a2子类对象/引用)强制转换成子类的引用
if(this.i == aa.i) //if ( 当前对象的 i 与 obj 的i相等)
return true;
else
return false;
}
}
- Note:
if (this.i == obj.i) cannot be written above, because the parent class object cannot directly call the specific properties / methods (members) of the child class
Test to see if you have rewritten equals:
String a1 = "123";
String a2 = "123";
System.out.println(a1.equals(a2));
//返回的是true, 说明类String 中的equals方法已经重写了
For strings, equals () compares what the string object points to, not the object itself.