Java程序设计-7-继承及接口.pptVIP

  • 32
  • 0
  • 约1.55万字
  • 约 62页
  • 2017-06-07 发布于湖北
  • 举报
修改hashCode( ) 对象相等,则他们的hashCode( )返回值相等 //返回对象的哈希码,用字符串studentid的哈希码表示,因为字符串的哈希码和它的串值有关 public int hashCode() { return (studentid != null ? studentid.hashCode() : 0); } 推荐的hashCode编码方法 对字段f,生成的int 根据其类型,c计算如下 boolean型: c=(f?0:1); byte,char,short or int型:c=(int)f; long型: c=(int)(f^(f32)); 无符号右移 float型: c=Float.floatToIntBits(f); double型:long l=Double.doubleToLongBits(f);c=(int)(l^(l32)); Object型:c=f.hashCode();eg.String s; c=s.hashCode() public int hashCode() { final int prime = 31; //一个素数 int result = 1; result = prime * result + ((birthDate == null) ? 0 : birthDate.hashCode()); result = prime * result + ((fullName == null) ? 0 : fullName.hashCode()); result = prime * result + gender; return result; } 总结:对象相等性判断 对于两个字符串,==返回true,例如hello==hello的结果是true。 对于两个对象引用变量,equals()比较的是逻辑意义,而不是判断两个引用变量是否是一个对象。但是==则判断的是两端的引用变量是否是引用一个对象。 String,Date,File 类和所有其它override equals()的包装类(Integer,Double,等等)将返回真。例如数值类对象和字符串对象之间的逻辑性相等判断,比较的是它们各自的状态(值),所以只要两个对象的值相同,equals()就返回true,但是只要不是引用的同一个对象,==返回false。 示例 //a和b虽然值相等,但是却各自引用了不同的对象 Integer a=new Integer(5); Integer b=new Integer(5); 则下面的语句正确吗? a==b ? a.equals(b) ? //str1和str2虽然值相等,但是却各自引用了不同的对象 String str1=new String(hello); String str2=new String(hello); String str3=str1; //两个变量指向同一个字符串对象 ?hello==hello“ ?new String(“hello”)==new String(“hello”) ? ?str1==str2 ?str1.equals(str2) ?str1==str3 ?str1.equals(str3) //student1和student2虽然逻辑上是一个学生,但实际上分别引用的是两个各自独立的对象 Student student1=new Postgraduate(200601001,Zhang-hua,Computer Science,AI); Student student2=new Postgraduate(200601001,Zhang-hua,Computer Science,AI); Student student3=student1;//两个变量指向同一个对象 ?student1== student2 ?student1.equals(student2) ?student1== student3 ?student1.equals(student3) 7.3.2抽象类 从Java语法上讲,抽象类是一种不能被直接实例化的类,如下面的类就是一个抽象类: public abstract class GeometricFigure{ String color; String getColor(){ Return this.color; } public abstract double getArea(); } 或者 public abstract class geometric{ String color; String

文档评论(0)

1亿VIP精品文档

相关文档