有关对象的比较方法
对于对象的比较可以通过不同的方法来实现:
1)== , 对于基本数据类型(int , double, float, long等)比较的是数值 ;对于引用类型(String,Double,Float,Long 等)比较的是内存地址(也就是当两个引用指向同一个地址时,这两个对象则相等)。
2)equal(对于对象的比较还可以通过重写equals方法来实现对对象的比较) ; 对于包装类型(Double,Floathe)以及String equal 比较的都是值是否相等 ;对于对象而言,如果没有重写equals方法,和==一样都是比较内存地址。
3)== 和 equal :
s1="java!!!";
s2=new String("java!!!");
s3="java";
s4="!!!";
s5="java"+"!!!";
s6=s3+s4;
上面代码s1==s2 false ; s1.equals(s2) true 这里s1的Java!!!是放在 常量池 中的 而new 出来的是存储在堆中的两者的内存空间是不同的。
s1==s6 false 这个由于 类加载初始化 问题,再编译期间是不能确定s3与s4 的值,只有在 运行时 才能确定。
3)该对象继承于 Comparable 并实现compareTo 这个方法(根据具体字段进行比较从而比较对象)。
public class test1 implements Comparable<test1>{
private int guest ;
public test1() {
}
@Override
public int compareTo(test1 o) {
// TODO Auto-generated method stub
if(o!=null&&(o instanceof test1)) { //判断不为空 以及 判断类型为该类型
test1 test=(test1)o;
return this.guest-test.guest;
}
return 1;
}
s1.compareTo(s2);
若返回的数大于表示 s1大于s2,返回数为0表示s1=s2.
重写equals方法时必须重写hashcode
1)在源码中规定:
/**
* Note that it is generally necessary to override the {@code hashCode}
* method whenever this method is overridden, so as to maintain the
* general contract for the {@code hashCode} method, which states
* that equal objects must have equal hash codes.
*
* @param obj the reference object with which to compare.
* @return {@code true} if this object is the same as the obj
* argument; {@code false} otherwise.
* @see #hashCode()
* @see java.util.HashMap
*/
public boolean equals(Object obj) {
return (this == obj);
}
可以看到如果重写equals方法,必须重写hashcode方法。规定了:如果两个对象相等,则两个对象的hashcode值是必须相等的。但是hashcode相等,两个对象不一定相同。