一:Collection與Collections的區別java
1.java.util.Collection是一個集合接口(集合類的一個頂級接口)。它提供了對集合對象進行基本操做的通用接口方法。Collection接口在Java類庫中有不少具體的實現。Collection接口的意義是爲各類具體的集合提供最大化的統一操做方式,其直接繼承接口有List與Set。以下:安全
public interface List<E> extends Collection<E> {}
public interface Set<E> extends Collection<E> {}
2.java.util.Collections是一個包裝類(工具類/幫助類)。它包含有各類關係集合操做的靜態多態方法。此類不能實例化(至於爲何不能實例化,參考源碼),就像一個工具類,用於對集合中元素進行排序,搜索以及線程安全等各類操做,服務於Java的Collection框架。框架
public class Collections { // Suppresses default constructor, ensuring non-instantiability. private Collections() { } }
二:接下來看看集合中對象容器的分類:工具
而後簡單瞭解下Collection中的主要方法:測試
1.定義一個Person類:線程
package com.berg.se.bean; public class Person { private String name; private int age; /** * 提供 構造方法,get set方法,hashCode 與 equals方法。 * */ }
2.測試:code
public class Test01Collection { @Test public void test1(){ //推薦使用泛型。 Collection<Person> collection = new ArrayList<Person>(); collection.add( new Person("Berg",22) ); collection.add( new Person("JavaSe",21)); System.out.println( "size: "+ collection.size() ); //collection.contains() :若是此 collection 包含指定的元素,則返回 true。 Person pe = new Person("Berg",22); //這裏須要Person類中重寫 hashCode()方法與wquals()方法。 boolean flag = collection.contains(pe); System.out.println( " 該元素是否存在 : " + flag ); //addAll(): Collection<Person> collection1 = new ArrayList<Person>(); collection1.add( new Person("BergBerg",22) ); collection1.add( new Person("JavaSe-Berg",21)); collection1.addAll(collection); System.out.println( collection1.size() ); /** * 在Collection中沒法獲取指定的元素,但能夠遍歷全部的元素 * 1.使用加強型for循環遍歷全部元素 * 2.使用Iterator迭代器 * 2.1 獲取迭代器對象:調用Collection的iterator()方法。獲取Iterator接口的對象。 * 2.2調用Iterator接口的方法進行迭代。 */ //1.使用加強型for循環遍歷全部元素 for (Person person : collection1) { System.out.println( person ); } System.out.println( "*********Iterator***********\n\n"); //2.使用Iterator迭代器 Iterator<Person> iterator = collection1.iterator(); //hasNext() : 表示若是仍有元素可迭代 ,則返回true。 while( iterator.hasNext() ){ Person p = iterator.next(); System.out.println( p ) ; } //如下將會拋出NoSuchElementException //Person p = iterator.next(); // 由於沒有元素能夠繼續迭代了。 } @Test public void test2(){ //注意List是實現Collection接口的 List list = new ArrayList(); int array[] = { 9,5,7,8,3,1,4,2,6 }; for (int i = 0; i < array.length; i++) { list.add(new Integer(array[i])); } Collections.sort(list); // 排序: 默認按升序進行排序。 for (int i = 0; i < array.length; i++) { System.out.print(list.get(i) + " "); } // 結果:23.0 111.0 112.0 231.0 456.0 } }