类集,Collection接口,List接口及其子类

类集的基本作用就是完成了一个动态的对象数组,里面的数据元素可以动态的增加。

类集中提供了以下的集中接口:

单值操作接口:Collection,List,Set,其中List和Set是Collection接口的子接口

对值的操作接口:Map

排序的操作接口:SortedMap,SortedSet

输出的接口:Iterator,ListIterator,Enumeration

队列:Queue

一,Collection接口

Collection接口是一个最重要的操作接口,其中规定了一个集合的基本操作方法,此接口下有两个子接口,这两个子接口又分别有着各自的特点。

Collection接口定义:

public interface Collection<E> extends Iterable<E>

Collection基本方法:

public boolean add(E e):向集合中增加元素

public boolean addAll(Collection<? exteds E> c):向集合中加入一组数据,泛型指定了操作上限

public void clear():清空所有的内容

public boolean contains(Object o):查找,判断是否有指定的内容

public boolean containsAll(Collection<?>c):查找一组数据是否存在

public boolean equals(Object o):对象比较

public int hashCode():返回hash码

public boolean isEmpty():判断集合是否为空

public Iterator<E> iterator():为Iterator接口实例化,迭代输出

public boolean remove(Object o):从集合中删除指定的对象

public boolean removeAll(Collection<?>c):从集合中删除一组对象

public int size():取得集合的长度

public Object[] toArray():取得全部的内容,以数组的形式返回

public <T> T[] toArray(T[] a):取得全部的内容

二,List接口

List接口最大的特点是里面的内容都允许重复,在Collection中新增的方法:

public void add(int index,E element):在指定的位置加入元素

public boolean addAll(int index,Collection<? extends E>c):在指定位置增加一组元素

public E get(int index):通过索引位置可以取出每一个元素

public ListIterator<E> listIterator():为ListIterator接口实例化

public E remove(int index):删除指定位置的内容

public E set(int index,E element):修改指定位置的元素

public List<E> subList(int formIndex,int toIndex):截取子集合

2.1 ArrayList类

ArrayList类是List接口中最常用的子类

使用ArrayList的对象可以直接为List接口实例化

import java.util.*;
public class ArrayListDemo {
 public static void main(String args[])
 {
  List<String> alist=new ArrayList<String>();
     alist.add("hello");
     alist.add(0,"world" );
     alist.remove(0);
     alist.remove("world");
     Object obj[]=alist.toArray(new String[]{});
//     for(int i=0;i<alist.size();i++)
//      System.out.println(alist.get(i));
     //System.out.println(alist.toString());
     for(int i=0;i<obj.length;i++)
     {
       String str=(String)obj[i];
       System.out.println(str);
     }
 }
}
以上在使用remove(Object obj)的时候操作使用的是String,所以可以删除掉,如果现在是一个自定义的匿名对象,则可能无法删除。

在Collection接口中实际上也规定了两个可以将集合变为对象数组的操作toArray()方法。

原文地址:https://www.cnblogs.com/jinzhengquan/p/1948515.html