import java.util.*;
public class TestBasic_collection{
public static void main(String[]args){
Collection c = new HashSet();
c.add("hello");
c.add(new Name1("1221", "11"));
c.add(new Integer(100));
System.out.println(c);
}
}class Name1{
 String firstName, lastName;
public Name1(String fristName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}

public String getFirstName(){
return firstName;
}
        public String getLastName(){
return lastName;
}

public String toString(){
return firstName + "  " +lastName ;
}
}输出:[hello, 100, null 11]可是这好像是错的, 应该输出的是:[hello, null 11, 100] 呀请大家 指教 指教

解决方案 »

  1.   

    构造函数内参数写错了
    this.firstName = firstName;
    应该为:
    this.firstName = fristName;
      

  2.   

    HashSet里元素的顺序是通过每个元素的哈希值得到的(调用object的hashCode()方法),和加入时的顺序无关。如果重写hashCode()方法的,hack一下元素在HashSet里的顺序是可以的。 ;-)