2019年1月21日-Hashcode和equals的认识

查看hahacode和equals的内部写法:

package cn.liu.three;

public class Student {
		private int id;
		private String name;
		
		@Override
		public int hashCode() {
			final int prime = 31;
			int result = 1;
			result = prime * result + id;
			return result;
		}
		@Override
		public boolean equals(Object obj) {
			if (this == obj)
				return true;
			if (obj == null)
				return false;
			if (getClass() != obj.getClass())
				return false;
			Student other = (Student) obj;
			if (id != other.id)
				return false;
			return true;
		}

测试haahcode和equals的使用方法:

当hashcode相同时,equals不一定为真。

当equals为真时,hashcode不一定相等。

判断equals是否为真时;先通过==判断地址是否一样若地址一样则为真,在判断内容是否一致,若内容相同则为真。返回true.

package cn.liu.three;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class testEquals {
	public static void main(String[] args) {
		List list=new ArrayList();
		String s1=new String("aaaa");
		String s2=new String("aaaa");
		list.add(s1);
		list.add(s2);
		System.out.println(list.size());
		
		
		Map map=new HashMap();
		map.put(s1, "AAA");
		map.put(s2, "BBB");
		System.out.println(map.get("aaaa"));
		
	}

}

猜你喜欢

转载自blog.csdn.net/qq_44370562/article/details/86591061