Java学习日记-11 集合(1)

时间:2023-03-08 22:59:50
Java学习日记-11 集合(1)

Collection接口
集合中存储的只是对象的引用,不是对象本身。

1.ArrayList<E>类
1.1ArrayList和Collection的关系
  public interface List<E>extends Collection<E>
  public class ArrayList<E> implements List<E>

1.2构造方法
   ArrayList() 构造一个初始容量为 10 的空列表。
   ArrayList(Collection<? extends E> c)构造一个包含指定 collection 的元素的列表,这些元素是按照

该 collection 的迭代器返回它们的顺序排列的。
   ArrayList(int initialCapacity)构造一个具有指定初始容量的空列表。

1.3基本方法
  boolean add(E e)将指定元素添加到列表尾部
  boolean addAll(Collection<? extends E> c) 将另一个集合中的元素全部添加到ArrayList中,允许重复

元素
  public boolean removeAll(Collection<?> c) 求补集A-B(从java.util.AbstractCollection 继承)
  void add(int index, E element)将指定元素插入指定位置
  void clear()移除所有元素
  boolean contain是(Object o)列表中如果包含该元素,返回true
  int indexOf(Object o)返回列表中首次出现指定元素的索引,不含该元素则返回-1
  boolean isEmpty() 列表为空,返回true
  E remove(int index)移除指定位置元素
  int size()返回元素数
  Object[] toArray()返回所有元素的数组
  <T> T[] toArray(T[] a)
(PS:集合可以直接打印输出)

2.迭代器Iterator
2.1 Collection中的iterator方法
  Iterator<E> iterator()返回在此 collection 的元素上进行迭代的迭代器。
2.2 Itetrator<E>接口
  boolean hasNext()仍有元素可以迭代,返回true
  E next() 返回迭代的下一个元素
  void remove()从迭代器指向的 collection 中移除迭代器返回的最后一个元素

 /*
 *利用Iterator遍历集合,假设集合coll中存放的都是String对象
 */
 Iterator it = coll.iterator();
 while(it.hasNext()){
     String s = (String)it.next();
     System.out.println(s);
 }

 //注意:在迭代的过程不能通过集合remove集合中的元素,否则会抛出
 java.util.ConcurrentModificationException并发修改异常,只能通过迭代器Iterator的remove方法移除当前迭代器指向的对象
 Iterator it = coll.iterator();
 while(it.hasNext()){
     String s = (String)it.next();
     if(s.equals("111")){
         coll.remove(s);    //这样不行,得改成it.remove()
     }
 }