在HashMap中,判断是否是同一个对象,需要根据equal和hashCode两个方法来判断

示例:

public class Test {
	public static void main(String[] args) throws IOException {
		
		
		Map<Entity,List> map1 = new HashMap<>();
		Entity entity1 = new Entity("张三","zhangsan");
		Entity entity2 = new Entity("王五","wangwu");
		map1.put(entity1, new ArrayList<>());
		map1.put(entity2, new ArrayList<>());
		
		Map<Entity,List> map2 = new HashMap<>();
		Entity entity3 = new Entity("张三","zhangsan");
		Entity entity4 = new Entity("李四","lisi");
		map2.put(entity3, new ArrayList<>());
		map2.put(entity4, new ArrayList<>());
		
		for(Entity entityIndex1 : map1.keySet()) {
			if(map2.keySet().contains(entityIndex1)) {
				System.out.println("相同"); //输出相同
			}
		}

	}
	
	private static class Entity{
		private String name;
		private String address;
		
		public Entity(String name, String address) {
			super();
			this.name = name;
			this.address = address;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getAddress() {
			return address;
		}
		public void setAddress(String address) {
			this.address = address;
		}
		
		@Override
		public boolean equals(Object obj) {
			
			if(obj==null)
			{
				return false;
			}
			
			if(obj==this)
			{
				return true;
			}
			
			if(obj instanceof Entity)
			{
				Entity otherR=(Entity) obj;
				
				if(otherR.getName().equals(this.getName()) && otherR.getAddress().equals(this.getAddress()))
				{
					return true;
				}
			}
			
			return false;
		}
		
		@Override
		public int hashCode() {
			// TODO Auto-generated method stub
			return getName().hashCode() + getAddress().hashCode();
		}
	}
}

  

posted @ 2021-11-25 11:41  信铁寒胜  阅读(194)  评论(0编辑  收藏  举报