【CXY】JAVA基礎 之 Collection

概述:

    1.Collection java集合框架的根級接口(root interface)

    2.常用子接口:List、Set、Queue,注意map是自成體系的

    3.方法:新增、包含、遍歷、交集、判空、大小、清空等

package com.cxy.collection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;

/**
 * @author chenxiaoyang
 */
public class CollectionTest
{
	/**
	 * 說明:
	 * 1.Collection java集合框架的根級接口(root interface)
	 * 2.常用子接口:List、Set、Queue,注意map是自成體系的
	 * 3.方法:新增、包含、遍歷、交集、判空、大小、清空等
	 */
	public static void main(String[] args)
	{
		Collection children=new ArrayList(); //注意由於這裏沒有加泛型,所以很多黃線警告
		//新增
		children.add("小明");
		children.add("小紅");
		children.add("小白");
		System.out.println("======================");
		
		//是否包含
		System.out.println("幼兒園一班是否有叫小明的小朋友? 答:"+children.contains("小明"));
		System.out.println("幼兒園一班是否有叫小黑的小朋友? 答:"+children.contains("小黑"));
		System.out.println("======================");
		
		
		//遍歷(2種方式)
		System.out.print("Iterator法遍歷:");
		Iterator it = children.iterator(); //Iterator(迭代器) 請參看博客中有關Iterator專門的文章
		while (it.hasNext())
		{
			System.out.print((String)it.next()+"  ");//由於沒有使用泛型,所以這裏需要強轉一下
		}
		System.out.println("");  //保持格式,無實際用處
		
		/*上面這種方式太注重遍歷過程的本身,對初學者來說有些複雜,那麼試試foreach吧
		 *foreach是java 5 提供的一種便捷遍歷方法
		 */
		System.out.print("foreach法遍歷:");
		for(Object one : children)
		{
			System.out.print((String)one+"  ");
		}
		System.out.println("");  //保持格式,無實際用處
		System.out.println("======================");
		
		
		//轉換成數組
		Object[] array=children.toArray();
		System.out.println("數組大小:"+array.length);
		System.out.println("======================");
		
		//刪除
		System.out.println("刪除前:"+children); //這種打印方法實際用的是Collection實現類的toString方法
		children.remove("小明");
		System.out.println("刪除後:"+children);
		System.out.println("======================");
		
		//交集
		Collection goodBoySet=new HashSet();  //一個set集合
		goodBoySet.add("小明");
		goodBoySet.add("小白");
		children.retainAll(goodBoySet);  //children集合中存在於goodBoySet集合的數據,簡單的講就是交集。
		System.out.println("交集結果:"+children);
		System.out.println("======================");
		
		//判空、大小、清空
		System.out.println("集合是否是空?答:"+children.isEmpty());
		System.out.println("集合大小:"+children.size());
		children.clear();
		System.out.println("清空後,集合是否是空?答:"+children.isEmpty());
		System.out.println("清空後,集合大小:"+children.size());
		System.out.println("======================");
	}
}


補充:

如果使用List的話,還可以使用序號遍歷方式

for(int i=0;i<children.size();i++)
{
    System.out.println("索引:"+i+":"+children.get(i));
}
當然這個的使用前提是children是List,上面例子的是Collection,所以需要轉下型:
for(int i=0;i<children.size();i++)
{
    System.out.println("索引:"+i+":"+((ArrayList)children).get(i));
}



相關文章連接:

《JAVA基礎 之 List》

《JAVA基礎 之 Map》

《JAVA基礎 之 Set》

《JAVA基礎 之 排序》

 

聲明:

1.原創文章,轉載請標明並加本文連接。

2.更詳盡的API請參見  http://docs.oracle.com/javase/7/docs/api/

3.文章反映個人愚見,如有異議歡迎討論指正 


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