import java.util.*;public class BasicContainer{
public static void main(String[] args){
Collection c=new HashSet();
c.add("hello");
c.add(new Name("l1","f1"));
c.add(new Integer(100));
System.out.println(c);
c.remove("hello");
c.remove(new Integer(100));
System.out.println(c.remove(new Name("l1","f1")));
System.out.println(c);
String s1=new String("A");
String s2=new String("A");
System.out.println(s1.equals(s2));
}
}class Name{
private String lastName,firstName;
Name(String ln,String fn){
lastName=ln;
firstName=fn;
} public String getlastName(){
return lastName;
} public String getfirstName(){
return firstName;
} public String toString(){
return lastName+" "+firstName;
} public boolean equals(Object obj){
if(obj instanceof Name){
Name name=(Name)obj;
return (lastName==name.lastName) && (firstName==name.firstName);
}//为什么这里写==和使用equals()是等价的
return super.equals(obj);
} public int hashCode(){
return firstName.hashCode();
}
}
public static void main(String[] args){
Collection c=new HashSet();
c.add("hello");
c.add(new Name("l1","f1"));
c.add(new Integer(100));
System.out.println(c);
c.remove("hello");
c.remove(new Integer(100));
System.out.println(c.remove(new Name("l1","f1")));
System.out.println(c);
String s1=new String("A");
String s2=new String("A");
System.out.println(s1.equals(s2));
}
}class Name{
private String lastName,firstName;
Name(String ln,String fn){
lastName=ln;
firstName=fn;
} public String getlastName(){
return lastName;
} public String getfirstName(){
return firstName;
} public String toString(){
return lastName+" "+firstName;
} public boolean equals(Object obj){
if(obj instanceof Name){
Name name=(Name)obj;
return (lastName==name.lastName) && (firstName==name.firstName);
}//为什么这里写==和使用equals()是等价的
return super.equals(obj);
} public int hashCode(){
return firstName.hashCode();
}
}
import java.util.*;public class BasicContainer{
public static void main(String[] args){
Collection c=new HashSet();
c.add("hello");
c.add(new Name("l1","f1"));
c.add(new Integer(100));
System.out.println(c);
c.remove("hello");
c.remove(new Integer(100));
System.out.println(c.remove(new Name(new String("l1"),new String("f1")))); System.out.println(c);
String s1=new String("A");
String s2=new String("A");
System.out.println(s1.equals(s2));
}
}class Name{
private String lastName,firstName;
Name(String ln,String fn){
lastName=ln;
firstName=fn;
} public String getlastName(){
return lastName;
} public String getfirstName(){
return firstName;
} public String toString(){
return lastName+" "+firstName;
} public boolean equals(Object obj){
if(obj instanceof Name){
Name name=(Name)obj;
return (lastName==name.lastName) && (firstName==name.firstName);
}
return super.equals(obj);
} public int hashCode(){
return firstName.hashCode();
}
}
结果
[100, hello, l1 f1]
false
[l1 f1]
true
改了System.out.println(c.remove(new Name(new String("l1"),new String("f1")))
那个地方必须使用equal,你用==对了是因为比较的两个字符串是在String池中取的同一个字符串,所以地址一样
== 是指的是比较的对象的地址是不相等
你自己在参考哈