set集合

  set接口和list接口繼承自collection接口,而set集合由set接口和set接口的實現類組成。

  set集合的特性:1,set集合中的對象不按特定的方式排序。

            2,set集合中不能包含重複的對象。

  set集合包含Hashset類和Tree類

  Hashset類:1,它不允許出現重複元素

         2,不保證和政集合中元素的順序

       3,允許包含值爲null的元素,但最多只能有一個null元素

public static void main(String[] args) {		
			   HashSet h=new HashSet();
		       h.add("1st");
		       h.add("2nd");
		       h.add(new Integer(3));
		       h.add(new Double(4.0));
		       h.add("2nd");            //重複元素,未被添加
		       h.add(new Integer(3));      //重複元素,未被添加
		       h.add(new Date());
		       System.out.println("size="+h.size());
		       Iterator it=h.iterator();	//set集合中的迭代器
		       while(it.hasNext()){		//遍歷集合,循環輸出結果
		    	   Object obj=it.next();
		    	   System.out.println(obj);
		       }
		}

 Tree類:TreeSet描述的是Set的一種變體——可以實現排序等功能的集合,它在講對象元素添加到集合中時會自動按照某種比較規則將其插入到有序的對象序列中。

  

public static void main(String [] args){
       TreeSet ts=new TreeSet();
       ts.add("小明");
       ts.add("小紅");
       ts.add("小黑");
       ts.add("小王");
 
       Iterator it=ts.iterator();
       while(it.hasNext())
       {
           String fruit=(String)it.next();
           System.out.println(fruit);
       }
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章