为什么hashcode和equals方法不适用于ArrayList?

时间:2019-07-11 10:26:37

标签: java arraylist hash

如果运行以下代码,则hashmap拒绝重复项,但ArrayList接受重复项。

为什么arraylist也使用hashcode()和equals()方法拒绝重复项?

public class EmpData {

	int Id; 
	String FirstName; 
	String LastName;
		
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((FirstName == null) ? 0 : FirstName.hashCode());
		result = prime * result + Id;
		result = prime * result + ((LastName == null) ? 0 : LastName.hashCode());
		return result;
	}



	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		
		EmpData other = (EmpData) obj;
		if (FirstName == null) {
			if (other.FirstName != null)
				return false;
		} else if (!FirstName.equals(other.FirstName))
			return false;
		if (Id != other.Id)
			return false;
		if (LastName == null) {
			if (other.LastName != null)
				return false;
		} else if (!LastName.equals(other.LastName))
			return false;
		
		return true;
	}

	


	@Override
	public String toString() {
		return "EmpData [Id=" + Id + ", FirstName=" + FirstName + ", LastName=" + LastName + "] \n";
	}



	public EmpData(int id, String firstName, String lastName) {
		Id = id;
		FirstName = firstName;
		LastName = lastName;
	}



	public static void main(String[] args) {
     
		EmpData obj1 = new EmpData(1,"Mk","Jk");
		EmpData obj2 = new EmpData(1,"Mk","Jk");
		
	    Map<EmpData,String> myMap = new HashMap<>(); myMap.put(obj1, "First");
		myMap.put(obj2, "Second");
		 
		System.out.println("Hashmap values are: " + myMap);
		
		ArrayList<EmpData> newArray = new ArrayList<>();
	
		newArray.add(obj1);		
		newArray.add(obj2);
		
		System.out.println("Array values are: " + newArray);
	
	}

}

上面的代码给出以下输出:

Hashmap values are: {EmpData [Id=1, FirstName=Mk, LastName=Jk] 
=Second}
Array values are: [EmpData [Id=1, FirstName=Mk, LastName=Jk] 
, EmpData [Id=1, FirstName=Mk, LastName=Jk] 
]

如何使Arraylist使用hascode()和equals()方法? 是否仅将hashcode和equals方法与hashmap一起使用?

1 个答案:

答案 0 :(得分:2)

ArrayList在调用诸如equals()int indexOf(Object o)之类的方法时确实使用boolean remove(Object o);,但它从未使用hashCode(),并且允许存在重复元素

是否覆盖hashCodeequals都没有关系。即使您多次向obj1添加了ArrayList,您最终也会得到List,该引用具有对同一对象的多个引用。

如果要消除重复项,可以使用HashSet(或LinkedHashSet)。