Java系列学习(十四)-集合

1.java中的集合学习

2.Collection中常用方法

1.添加功能

boolean add(E e):添加一个元素

boolean addAll(Collection<? extends E> c):添加一个集合

2.删除功能

void clear():移除所有元素

boolean remove(Object o):移除一个指定元素

boolean removeAll(Collection<?> c):移除指定集合中的元素【只要有元素被移除,就返回true】

3.判断功能

boolean contains(Object o):判断集合中是否包含指定元素

boolean containsAll(Collection<?> c):判断集合中是否包含指定集合元素【只有全部包含,才返回true】

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

boolean equals(Object o)

4.获取功能

Iterator<E> iterator():【父类中继承的方法】

int hashCode():返回集合的哈希值

5.长度功能

int size():获取集合中元素的个数

6.交集功能

boolean retainAll(Collection<?> c):两个集合的交集【A对B做交集,结果保存在A中;只有A不变,才返回true】

7.把集合转换成数组

Object[] toArray():把集合转换成数组,可实现集合的遍历

<T> T[] toArray(T[] a):

3.List特有的方法

1.添加功能

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

boolean addAll(int index, Collection<? extends E> c):在指定位置添加集合

2.获取功能

E get(int index):获取指定位置的元素【与size()结合可实现遍历】

List<E> subList(int fromIndex, int toIndex)

int indexOf(Object o)

int lastIndexOf(Object o)

3.列表迭代器

ListIterator<E> listIterator():List集合特有的迭代器

ListIterator<E> listIterator(int index)

4.删除功能

E remove(int index):根据索引删除元素,返回被删除的元素

5.修改功能

E set(int index, E element):根据索引修改元素,返回被修改的元素

4.Vector特有的功能

1.添加功能

public void addElement(E obj)

public void insertElementAt(E obj, int index)

2.获取功能

public E elementAt(int index)

public Enumeration<E> elements()

public int capacity():获取集合的容量

public int indexOf(Object o, int index)

public int lastIndexOf(Object o, int index)

public E firstElement():获取集合第一个元素

public E lastElement():获取集合最后一个元素

3.复制功能

public void copyInto(Object[] anArray)

4.修改功能

public void ensureCapacity(int minCapacity):增加集合的容量

public void setElementAt(E obj, int index)

public void trimToSize():使集合等于当前大小

public void setSize(int newSize):设置集合的大小

5.移除功能

public void removeAllElements():移除所有元素,并大小设置为零

public boolean removeElement(Object obj):移除第一个元素

public void removeElementAt(int index):移除指定元素

protected void removeRange(int fromIndex, int toIndex):移除指定范围元素【包括fromindex,不包括toIndex】

6.格式化功能

public String toString():返回集合的字符串形式【看源码,重写了】

LinkedList特有的方法:(可实现自定义栈)

public class LinkedList<E>extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, Serializable

1.添加功能

public void addFirst(E e)

public void addLast(E e)

2.获取功能

3.public E getLast()

4public E getLast()

3.删除功能

public E removeFirst()

public E removeLast()

更多精彩内容请看:http://www.cnblogs.com/2star
原文地址:https://www.cnblogs.com/kimisme/p/4665483.html