zoukankan      html  css  js  c++  java
  • 在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();
    		}
    	}
    }
    

      

  • 相关阅读:
    XP显示桌面
    批量改名
    poj 3126 BFS
    poj 3278 BFS
    poj 1426 BFS
    准备打酱油…
    POJ 2243 BFS 和 简单的调试方法学习
    K
    EXCEL fundamentals
    poj 1011 DFS+剪枝
  • 原文地址:https://www.cnblogs.com/wwssgg/p/15601993.html
Copyright © 2011-2022 走看看