Java 集合框架小结
Java 集合框架(Java Collections Framework,JCF),它主要由一组用来操作对象的接口组成的.
集合接口有如下几种:
Collection接口:定义了存取一组对象的方法,其子接口Set和List分别定义了存储方式
Set接口:Set中的数据对象没有顺序且不可以重复
List接口:List中的数据对象有顺序且可以重复
Map接口定义了存储"键(key)-值(value)映射对"的方法
一 Collection接口中所定义的方法:
boolean add(E e)
确保此 collection 包含指定的元素(可选操作)。
boolean addAll(Collection<? extends E> c)
将指定 collection 中的所有元素都添加到此 collection 中(可选操作)。
void clear()
移除此 collection 中的所有元素(可选操作)。
boolean contains(Object o)
如果此 collection 包含指定的元素,则返回 true。
boolean containsAll(Collection<?> c)
如果此 collection 包含指定 collection 中的所有元素,则返回 true。
boolean equals(Object o)
比较此 collection 与指定对象是否相等。
int hashCode()
返回此 collection 的哈希码值。
boolean isEmpty()
如果此 collection 不包含元素,则返回 true。
Iterator<E> iterator()
返回在此 collection 的元素上进行迭代的迭代器。
boolean remove(Object o)
从此 collection 中移除指定元素的单个实例,如果存在的话(可选操作)。
boolean removeAll(Collection<?> c)
移除此 collection 中那些也包含在指定 collection 中的所有元素(可选操作)。
boolean retainAll(Collection<?> c)
仅保留此 collection 中那些也包含在指定 collection 的元素(可选操作)。
int size()
返回此 collection 中的元素数。
Object[] toArray()
返回包含此 collection 中所有元素的数组。
<T> T[] toArray(T[] a)
返回包含此 collection 中所有元素的数组;返回数组的运行时类型与指定数组的运行时类型相同。
二 Iterator接口
所有实现了Collection接口的容器类都有一个iterator方法用以返回一个实现了Iterator接口的对象
Iterator对象称作迭代器,用以方便的实现对容器内元素的遍历操作.
Iterator接口定义了如下方法:
boolean hasNext()
如果仍有元素可以迭代,则返回 true。
E next()
返回迭代的下一个元素。
void remove()
从迭代器指向的 collection 中移除迭代器返回的最后一个元素(可选操作)。
下面举例说明Collection和迭代器的一些常见用法:
/** * 测试常用集合类的用法 */package com.basic.collection;import java.util.Collections;import java.util.HashMap;import java.util.HashSet;import java.util.LinkedList;import java.util.List;import java.util.Map;import java.util.Set;/** * @author Administrator * * @version 2009-05-06 */public class TestExample { /** * @param args */ public static void main(String[] args) { //Set接口的常见方法应用 Set s = new HashSet(); s.add("hello"); s.add("world"); s.add(new Integer(100)); s.add("hello"); //相同的元素不会被加入 System.out.println(s); //List接口的常见方法应用 List l1 = new LinkedList(); //下标从0开始 for (int i=0; i<=5; i++) { l1.add("a"+i); } l1.add(3,"a100"); l1.set(6, "a200"); l1.remove(1); //Collections类的常见方法应用 Collections.shuffle(l1); //随机排列 Collections.sort(l1); //排序 Collections.reverse(l1); //逆续 Collections.sort(l1); //排序 System.out.println(Collections.binarySearch(l1,"a2")); //折半查找,必须先对集合升序排序才可以进行折半查找 //Map接口的常见访求应用 Map m1 = new HashMap(); Map m2 = new HashMap(); m1.put("one", new Integer(1)); m1.put("two", new Integer(2)); m1.put("three", new Integer(3)); m2.put("A", new Integer(1)); m2.put("B", new Integer(2)); System.out.println(m1.size()); System.out.println(m1.containsKey("one")); System.out.println(m2.containsValue(new Integer(1))); if (m1.containsKey("two")) { int i = ((Integer) m1.get("two")).intValue(); System.out.println(i); } Map m3 = new HashMap(m1); m3.putAll(m2); System.out.println(m3); }}