在 Java 8 中(需要覆盖 hashCode() 和 equals(Object obj) 方法):
cat c1=new cat("lolo", "black");
cat c3=new cat("lolo", "black");
List<Object> arrayList = new ArrayList<Object>();
arrayList.add(c1);
arrayList.add(c3);
List<Object> deduped = arrayList.stream().distinct().collect(Collectors.toList());
旧 Java 版本:
如果你想消除重复的对象使用HashSet并且必须实现(覆盖)hashCode()方法:
public class cat {
String name;
String color;
public cat(String name, String color) {
super();
this.name = name;
this.color = color;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((color == null) ? 0 : color.hashCode());
result = prime * result + ((name == null) ? 0 : name.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;
cat other = (cat) obj;
if (color == null) {
if (other.color != null)
return false;
} else if (!color.equals(other.color))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public static void main(String[] args) {
cat c1=new cat("lolo", "black");
cat c2=new cat("lolo2", "white");
cat c3=new cat("lolo", "black");
List<Object> arrayList = new ArrayList<Object>();
arrayList.add(c1);
arrayList.add(c3);
Set<Object> uniqueElements = new HashSet<Object>(arrayList);
arrayList.clear();
arrayList.addAll(uniqueElements);
System.out.println(arrayList.size());//will be 1
}
}
如果您需要更多信息如何做好hashcode(),您可以阅读此答案:Best implementation for hashCode method
如果所有对象类都实现(覆盖)equal() 方法,则可以使用它。
示例:
public class cat {
String name;
String color;
public cat(String name, String color) {
super();
this.name = name;
this.color = color;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
cat other = (cat) obj;
if (color == null) {
if (other.color != null)
return false;
} else if (!color.equals(other.color))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public static void main(String[] args) {
cat c1=new cat("lolo", "black");
cat c2=new cat("lolo2", "white");
cat c3=new cat("lolo", "black");
Object o1=c1;
Object o2=c2;
Object o3=c3;
System.out.println(o1.equals(o2));//false
System.out.println(o1.equals(o3));//true
}
}