//我有一个List,里面存有自己定义的类型Group
Group group = new Group();
List list = new ArrayList();
list.add(group);
//然后转换到一个Set里面去
Set set = new HashSet(list);
//然后判断group是否在set中
set.contains(group); // 为什么这里每次都得到false?
Group group = new Group();
List list = new ArrayList();
list.add(group);
//然后转换到一个Set里面去
Set set = new HashSet(list);
//然后判断group是否在set中
set.contains(group); // 为什么这里每次都得到false?
public void test(){
// 我有一个List,里面存有自己定义的类型Group
String group = new String();
List list = new ArrayList();
list.add(group);
// 然后转换到一个Set里面去
Set set = new HashSet(list);
// 然后判断group是否在set中
System.out.println(set.contains(group)); // 为什么这里每次都得到false?
}-------------------------
console: true
import java.util.*;public class test3 {
public test3() {
} public static void main(String[] args){
String xx = new String("1");
String yy = new String("2");
List list = new ArrayList();
list.add(xx);
Set set = new HashSet(list);
System.out.println(set.contains(xx));
System.out.println(set.contains(yy));
}
}——————————————————————————————————
true
false
你的问题很简单,就是你的自己定义的类里面没有override :public int hashCode()和public boolean equals(Object t)这两个函数。
import java.text.*;
class Ball{
}public class Untitled4 {
public static void main(String[] args) throws Exception{
Ball ball = new Ball();
List list = new ArrayList();
list.add(ball);
System.out.println(list.contains(ball));
Set set = new HashSet(list);
System.out.println(set.contains(ball));
}
}返回两个truefaen(发恩):你说的是不必要的,如果没有orerride equals和hashCode,就会使用Object的版本,是可以工作的。只不过Object的版本使用的是最为严格的比较:内存地址。