主要内容
2个根接口Collection和Map
方法:
1. boolean addAll(Collection< ? extends E> c)把c容器的元素全部添加到当前容器中(并集)
2. boolean removeAll(Collection< ? extends E> c)从当前容器中把和c容器中元素相同的元素删除掉(差集)
3. boolean retainAll(Collection< ? extends E> c)求容器c和当前容器中的相同元素(交集)
4. Iterator<E> iterator() 用于返回一个当前容器的迭代器,用于对当前容器进行遍历
LinkedList中有listIterator方法,返回一个ListIterator类型的迭代器,可以按任一方向遍历列表,如下图所示:
ListIterator的示例程序
Collection接口泛化出3个主要子接口:Set、List、Queue, Set容器中不能有重复元素,List中可以有,通常是有序的,Queue容器用于存储先进先出类型的数据。
Set接口的具体类: HashSet(数据无序)、LinkedSet、TreeSet(集合中数据已排好序)
List接口的具体类: ArrayList、LinkedList、Stack、Vector等
Queue接口有一个子接口,Deque, 它的具体类主要是PriorityQueue。
容器的构造方法:
1. 无参的空构造方法,构造一个空的容器,没有任何元素:
a) HashSet<String> hashSet=new HashSet<String>()
b) List<String> list=new LinkedList<String>()
2. 构造方法参数为已有的Collection对象,用已有的容器构造一个新的容器
a) TreeSet<String> treeSet=new TreeSet<String>(hashSet); (这里的好处:可以将无序变为有序)
b) List <String> list01=new ArrayList<String>(list);
3. 使用类Arrays中的asList方法将一个数组转换为一个容器,范围值为固定长度的容器转换后得到的是一个一个固定大小的List,不可以对其进行进行修改操作,否则会出席UnSupportedOperationException的异常
a) String []nums={"one","two","three"};
List<String> list03=Arrays.asList(nums);
此时如果执行,list03.add(“four”);就会发生异常
b) HashSet<String> hashSet01=new HashSet<String>(Arrays.asList(“one”,”two”));
如下图所示:
类Collections,有很多static类型的方法,如sort、reverse等
http://www.yingxiao1314.com