"java.util.NoSuchElementException: No value present" 问题解决:重写hashCode 和 equals 方法

来源:互联网 发布:战地4 FY-js 狙击枪 编辑:程序博客网 时间:2024/05/17 06:38

java.util.NoSuchElementException: No value present



问题解决:重写hashCode  和  equals 方法


/* * 重写equals必须注意:                   *     1 自反性:对于任意的引用值x,x.equals(x)一定为true          *     2 对称性:对于任意的引用值x 和 y,当x.equals(y)返回true,y.equals(x)也一定返回true          *     3 传递性:对于任意的引用值x、y和z,如果x.equals(y)返回true,并且y.equals(z)也返回true,         *               那么x.equals(z)也一定返 回 true          *     4 一致性:对于任意的引用值x 和 y,如果用于equals比较的对象信息没有被修改,         *               多次调用x.equals(y)要么一致地返回true,要么一致地返回false         *     5 非空性:对于任意的非空引用值x,x.equals(null)一定返回false *  * 注意: 重写equals方法后最好重写hashCode方法,         *       否则两个等价对象可能得到不同的hashCode,这在集合框架中使用可能产生严重后果 *//* * 1.重写equals方法修饰符必须是public,因为是重写的Object的方法.          * 2.参数类型必须是Object. */@Overridepublic boolean equals(Object other) {if (this == other) { // 先检查是否其自反性,后比较 other 是否为空。这样效率高return true;}if (other == null) {return false;}if (!(other instanceof Student))return false;final Student s = (Student) other;if (studentNum == null) {if (s.getStudentNum() != null) {return false;}} else if (!studentNum.equals(s.getId())) {return false;}if (name == null) {if (s.getName() != null) {return false;}} else if (!name.equals(s.getName())) {return false;}//几项检查都没问题 返回truereturn true;}@Overridepublic int hashCode() {  //hashCode主要是用来提高hash系统的查询效率。当hashCode中不进行任何操作时,可以直接让其返回 一常数,或者不进行重写。final int prime = 29;int result = 1;result = prime * result + ((studentNum == null) ? 0 : studentNum.hashCode());result = prime * result + ((name == null) ? 0 : name.hashCode());return result;}


0 0
原创粉丝点击