Collection在英文单词的意思是:采集,收集。而在JAVA API 文档中它是一个收集数据对象的容器。
Collection作为容器类的根接口。如下图(部分子接口未写出):
文档中说明了Collection接口,有如下的方法:
boolean | add(E e)
Ensures that this collection contains the specified element (optional operation).
|
boolean | addAll(Collection<? extendsE> c)
Adds all of the elements in the specified collection to this collection (optional operation).
|
void | clear()
Removes all of the elements from this collection (optional operation).
|
boolean | contains(Object o)
Returns true if this collection contains the specified element.
|
boolean | containsAll(Collection<?> c)
Returns true if this collection contains all of the elements in the specified collection.
|
boolean | equals(Object o)
Compares the specified object with this collection for equality.
|
int | hashCode()
Returns the hash code value for this collection.
|
boolean | isEmpty()
Returns true if this collection contains no elements.
|
Iterator<E> | iterator()
Returns an iterator over the elements in this collection.
|
boolean | remove(Object o)
Removes a single instance of the specified element from this collection, if it is present (optional operation).
|
boolean | removeAll(Collection<?> c)
Removes all of this collection's elements that are also contained in the specified collection (optional operation).
|
boolean | retainAll(Collection<?> c)
Retains only the elements in this collection that are contained in the specified collection (optional operation).
|
int | size()
Returns the number of elements in this collection.
|
Object[] | toArray()
Returns an array containing all of the elements in this collection.
|
<T> T[] | toArray(T[] a)
Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.
|
下面代码示范List继承collection接口并实现它部分的相关方法:
<pre name="code" class="java"> package CrazyStone;
import java.util.ArrayList;
import java.util.List;
public class DemoList {
public static void main(String[] args) {
int value;
List list=new ArrayList(); //定义List类对象list,并实现父类引用;
list.add("CSDN"); //添加数据对象方法;
list.add("GB记忆");
System.out.println( list.isEmpty()); //判断list容器是否为空
value=list.size(); //返回容器的大小;
for(int i=0;i<value;i++) //遍历容器;
{ String str =(String) list.get(i);
System.out.println(str);
}
System.out.println("---------------------");
//跟顺序有关的操作
list.remove(0); //在容器中移出CSDN,但并未删除;
list.set(0, "CSDNGO"); //向容器中插入对象;
list.add("加油!");
value=list.size();
for(int i=0;i<value;i++) //遍历容器;
{ String str =(String) list.get(i);
System.out.println(str);
}
}
}