1.String池
观察对象相等:
public class SyringDemo3 {
public static void main(String[] args) {
String a = "Hello";
String b = "Hello";
String c = new String("Hello");
String d = new String("Hello");
System.out.println("a==b 为 " + (a == b));
System.out.println("b==c 为 " + (b == c));
System.out.println("c==d 为 " + (c == d));
}
}
//a==b 为 true
b==c 为 false
c==d 为 false
2.equals和hashcode
*equals()相等的两个对象,hashcode()一定相等,反过来,hashcode()不等,一定能推出equals()也不等,hashcode()相等,equals()可能相等,也可能不等
*如果a.equals(b)返回是“true”,那么b.equals(a)也应该返回是“true”
a.equals(a)必须返回是“true”
如果a.equals(b)返回是“true”,而且b.equals(c)返回是“true”,那么c.equals(a)也应该返回是“true”
如果a.equals(b)返回是“true”,只要a和b内容一直不变,返回都是“true
任何情况下,a.equals(null),永远返回是“false”,a.equals(不同于a)永远返回是“false”
*public class Person
{
private String name;
private int age;
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (name == null)
{
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
3.明天学习内容:StringBuffer类的使用