下面这个小程序打印出的为什么是true和false啊,求大神分析一下,万分感谢~

问题描述:

public class BasicContainer {
public static void main(String[] args) {
Collection c = new HashSet();
c.add("hello");
c.add(new Name("lu","dongdong"));
c.add(new Integer(100));
System.out.println(c.remove(new Integer(100)));
System.out.println(c.remove(new Name("lu","dongdong")));
}
}

class Name {
private String firstName,lastName;
Name(String firstName,String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String toString() {
return firstName + " " + lastName;
}
}

打印出的就是:
true
false

很简单,Hashset的Remove会执行equals方法去比较传入的参数和内部存储的参数,相同的删除返回true,找不到返回false

而class类型比较的是引用,即便每个字段相同,两个对象还是不同的,所以你传一个new的对象,返回false。
而integer比较的是值,只要里面存的是100,你传入100,就相同,就能删除。

remove(Component comp)
从此容器中移除指定组件。
void remove(int index)
从此容器中移除 index 指定的组件。