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

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.
	 */
	@Override
	public 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;
		}
		

		//几项检查都没问题 返回true
		return true;
	}

	@Override
	public 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
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值