AwkingのBlog
行己所爱 爱己所行
2025 年 9 月
17
Wednesday
白日梦想出版社
AwkingのBlog
行己所爱 爱己所行
白日梦想出版社
list,queue,deque容器通过equals方法判定,set和map容器通过equals和hashcode判定
例如声明一个Test
类,该对象中有类型为String
的成员变量name
,若创建两个Test
对象分别为t1
和t2
,list容器如何判断两者是同一个对象呢?
用equals
方法进行比较,我们需要对Test
中的equals
方法进行重写
public class test {
public static void main(String[] args) {
Test t1 = new Test("A");
Test t2 = new Test("A");
List list = new ArrayList<>();
list.add(t1);
list.remove(t2);
System.out.println(list);
}
static class Test{
String name;
public Test(String str) {
this.name = str;
}
public boolean equals(Object obj){
return this.name.equals(((Test) obj).name);
}
}
}
从上面的代码中,t1
和t2
显然不是同一个对象,我们通过重写修改equals
方法,将name
相同的不同对象认为是同一个对象,向list添加t1
,删除t2
,最后发现成功删除list中的t1
,说明list容器判断t1
和t2
是同一个对象
但是set或map容器还需要重写hashcode
方法
public class test { public static void main(String[] args) { Test t1 = new Test("A"); Test t2 = new Test("A"); Set<Test> set = new HashSet<>(); System.out.println(set.add(t1)); System.out.println(set.add(t2)); System.out.println(set); } static class Test{ String name; public Test(String str) { this.name = str; }
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Test test = (Test) o; return Objects.equals(name, test.name); } @Override public int hashCode() { return Objects.hash(name); } }
}