日期:2014-05-20  浏览次数:20719 次

HashSet的小问题..
class   WrappedString   {
    private   String   s;
    public   WrappedString(String   s)   {   this.s   =   s;   }

    public   static   void   main(String[]   args)   {
          HashSet <Object>   hs   =   new   HashSet <Object> ();

          String   s1   =   new   String( "gg ");
          String   s2   =   new   String( "gg ");

          hs.add(s1);  
          hs.add(s2);
          System.out.println(hs.size());  
    }  
}输出为1

class   WrappedString   {
    private   String   s;
    public   WrappedString(String   s)   {   this.s   =   s;   }

    public   static   void   main(String[]   args)   {
          HashSet <Object>   hs   =   new   HashSet <Object> ();
          WrappedString   ws1   =   new   WrappedString( "aardvark ");
          WrappedString   ws2   =   new   WrappedString( "aardvark ");

          hs.add(ws1);
          hs.add(ws2);
          System.out.println(hs.size());  
    }  
}输出为2       //??????why


为什么呢?

------解决方案--------------------
String 重写过equals和hasCode,你可以看一下Strintg
WrappedString 没有重写过。。
hashSet 判断两个对象是否相等,是通过equals和hasCode进行判断的

所以。。。。