Collection
Collection
Collection(接口)
/ \
/ \
List Set(接口)
/ \ \
ArrayList LinkedList HashSet (实现类)
\
LinkedHashSet (实现类)
ArrayList
(数组实现)特点:
- 有索引,有序
- 查询速度快,增删速度慢
LinkedList
(链表实现)特点:
- 有索引,有序
- 查询速度慢,增删速度快
HashSet
(数组+链表实现)特点:
- 无索引,无序,不允许存在重复的值
- 查询速度快
LinkedHashSet
(数组+红黑树实现)特点:
- 有索引,有序,不允许存在重复的值
- 查询速度快
Collection常用方法
public boolean add(E e) //将对象添加到集合中
public boolean remove(Object o) //删除指定对象
public boolean isEmpty() //判断集合是否为空
public void clear() //清空集合
public int size() //获取集合的元素个数
public boolean contains(Object o) //集合中是否包含指定对象
public Object[] toArray() //将集合转换为数组
迭代器
while进行迭代
public static void main(String[] args) {
Collection<String> coll = new ArrayList<>();
coll.add("a");
coll.add("b");
coll.add("c");
Iterator<String> i = coll.iterator();
//使用while进行迭代
while(i.hasNext())
{
System.out.println(i.next());
}
}
for进行迭代
public static void main(String[] args) {
Collection<String> coll = new ArrayList<>();
coll.add("a");
coll.add("b");
coll.add("c");
for (Iterator<String> i = coll.iterator();i.hasNext();) {
System.out.println(i.next());
}
}
增强for循环
public static void main(String[] args) {
String[] str = {"a","b","c"};
for (String i:
str) {
System.out.println(i);
}
}
List
List常用接口
void add(int index, E element)
E get(int index)
E set(int index, E element)
E remove(int index);
int indexOf(Object o)
int lastIndexOf(Object o)
List<E> subList(int fromIndex, int toIndex)
ArrayList接口
实现List接口
LinkedList常用接口
public void addFirst(E e) 等价于 public void push(E e)
public void addLast(E e)
public E getFirst()
public E getLast()
public E removeFirst() 等价于 public E pop()
public E removeLast()