Collection是Java集合体系中的根接口,Collection表示一组对象(不能是基本数据类型),有些collection是可以有重复元素的,有些不可以,有些是有序的,有些是无序的。
直接继承Collection的接口有List,Queue,Set。
List是支持随机访问的顺序表。
Queue是先进先出的顺序表。
Set并没有添加一些特殊的方法,可以看成简单的集合。
Collection中定义了一些方法,继承Collection的类都要实现这些方法:
返回元素的数量
// Query Operations
/**
* Returns the number of elements in this collection. If this collection
* contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
*
* @return the number of elements in this collection
*/
int size();
判断集合内是否有元素
/**
* Returns <tt>true</tt> if this collection contains no elements.
*
* @return <tt>true</tt> if this collection contains no elements
*/
boolean isEmpty();
判断是否含有某个元素
/**
* Returns <tt>true</tt> if this collection contains the specified element.
* More formally, returns <tt>true</tt> if and only if this collection
* contains at least one element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>.
*
* @param o element whose presence in this collection is to be tested
* @return <tt>true</tt> if this collection contains the specified
* element
* @throws ClassCastException if the type of the specified element
* is incompatible with this collection
* (<a href="#optional-restrictions">optional</a>)
* @throws NullPointerException if the specified element is null and this
* collection does not permit null elements
* (<a href="#optional-restrictions">optional</a>)
*/
boolean contains(Object o);
返回一个迭代器
/**
* Returns an iterator over the elements in this collection. There are no
* guarantees concerning the order in which the elements are returned
* (unless this collection is an instance of some class that provides a
* guarantee).
*
* @return an <tt>Iterator</tt> over the elements in this collection
*/
Iterator<E> iterator();
返回一个包含所有元素的数组,元素类型是Object
/**
* Returns an array containing all of the elements in this collection.
* If this collection makes any guarantees as to what order its elements
* are returned by its iterator, this method must return the elements in
* the same order.
*
* <p>The returned array will be "safe" in that no references to it are
* maintained by this collection. (In other words, this method must
* allocate a new array even if this collection is backed by an array).
* The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all of the elements in this collection
*/
Object[] toArray();
类似的有支持泛型的toArray方法,返回值类型是制定数组的数据类型。
<T> T[] toArray(T[] a);
用法为:
public static void main(String[] args) throws IOException {
List<Integer> list=new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
Integer[] ans=list.toArray(new Integer[list.size()]);
for(int i=0;i<3;i++){
System.out.println(ans[i]);
}
}
输出
1
2
3
像之前提到的,不能转换成int数组,因为int是基本数据类型。
添加元素
boolean add(E e);
移除元素
boolean remove(Object o);