程序如下:
package dataStruct.set;import java.util.*;public class TestSet { /**
 * @param args
 */
public static void main(String[] args) {
// TODO 自动生成方法存根
 Set set = new HashSet(); 
             String str1 = new String("123");
             String str2 = new String("456");
             String str3 = new String("123");
 set.add(str1);
 set.add(str2);
 set.add(str3);
 Iterator  it =  set.iterator();
while(it.hasNext()){
 System.out.println(it.next());   
 }

   Set set1 = new HashSet(); 
    set1.add(new String("abc"));    
set1.add(new String("xyz"));    
set1.add(new String("abc"));  
Iterator iter = set1.iterator();    
         while(iter.hasNext())    
 {    
   System.out.println(iter.next());    
 }    
}}
测试输出为:
123
456
xyz
abc
奇怪之处就在于第二个为啥不是abc在前xyz在后呢?而且就是这个abc有点特殊,其他的都好啦,有没有高手给看看到底是咋回事?set接口判断重复的基准是啥?到底为啥呢?整了半天也没弄清楚到底是啥问题,高手指点啊!

解决方案 »

  1.   

    hashset 中的顺序不是按add顺序的,除非你用LinkedHashSet
      

  2.   

    具体加入hash表中的第几项不是按加入的顺序来的,而是根据计算的hashCode来处理的.
    可以联系一下数据结构中往一个hash表中增加项目的处理方法.
      

  3.   

    因为HashSet内部是使用的HashMap,你可以自己跟代码看看:public V put(K key, V value) {
    if (key == null)
        return putForNullKey(value);
            int hash = hash(key.hashCode());
            int i = indexFor(hash, table.length);  //产生对应的存放位置
        //查找是不是已经加入了这个Key
            for (Entry<K,V> e = table[i]; e != null; e = e.next) {
                Object k;
                if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                    V oldValue = e.value;
                    e.value = value;
                    e.recordAccess(this);
                    return oldValue;
                }
            }        modCount++;
       //如果没有,加入该项,这里的i就是指定在HashMap中使用的用来存储数据的下标,从代码上面看,根据hash计算i
            addEntry(hash, key, value, i);
            return null;
        }