码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-10-27 23:49:58      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:

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 中移除迭代器返回的最后一个元素

 1 /*
 2 *利用Iterator遍历集合,假设集合coll中存放的都是String对象
 3 */
 4 Iterator it = coll.iterator();
 5 while(it.hasNext()){
 6     String s = (String)it.next();
 7     System.out.println(s);
 8 }
 9 
10 //注意:在迭代的过程不能通过集合remove集合中的元素,否则会抛出
11 java.util.ConcurrentModificationException并发修改异常,只能通过迭代器Iterator的remove方法移除当前迭代器指向的对象
12 Iterator it = coll.iterator();
13 while(it.hasNext()){
14     String s = (String)it.next();
15     if(s.equals("111")){
16         coll.remove(s);    //这样不行,得改成it.remove()
17     }
18 }

 

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

标签:

原文地址:http://www.cnblogs.com/youilika/p/4915873.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!