数组有长度限制,有时候使用起来不方便
类集是一个动态的对象数组,不受对象数组长度的限制(同一类型且长度不固定)
类集常用接口:
Collection接口:存放同一类型值的最大父类
int size();
boolean isEmpty();
boolean contains(Object o);
Iterator<E> iterator();
Object[] toArray();
<T> T[] toArray(T[] a);
boolean containsAll(Collection<?> c);
boolean add(E e);
boolean remove(Object o);
boolean addAll(Collection<? extends E> c);
boolean removeAll(Collection<?> c);
void clear();
boolean equals(Object o);
int hashCode();
和数组共有特性:长度、添加、删除、搜索、元素遍历、排序
Collection的父类接口Iterable接口:
Iterator<T> iterator()
Collection的子类接口List接口独有的抽象方法【跟下标有关】:
E get(int index);
E set(int index,E element);
void add(int index, E element);
E remove(int index);
int indexOf(Object o);
int lastIndexOf(Object o);
ListIterator<E> listIterator();
ListIterator<E> listIterator(int index);
List<E> subList(int fromIndex, int toIndex);
List的实现类ArrayList类:
ArrayList<String> list = new ArrayList<String>();
List<String> list = new ArrayList<String>();
一般实现类实例化都是多态上转
集合输出三种方式:
1)foreach循环和for循环
2)Iterator()——调Collection接口下的抽象方法,返回Iterator<E>
抽象方法:
boolean hasNext();
E next(); // 取出当前元素
void remove();
Iterator<String> tmp1 = list.iterator();
while(trmp1.hasNext){
String value = temp.next();
System.out.print(value)
}
3)【仅限List集合】ListIterator()——调List接口下的抽象方法,返回ListIterator<E>
抽象方法:
boolean hasPrevious();
E previous(); // 取出当前元素
int nextIndex(); // 可从后往前取元素
int previousIndex();
ListIterator<String> iter = list.listIterator();
while(iter.hasPrevious()){ // 从后往前输出
String value = iter.previous();
System.out.println(value)
}
List接口特点:
线性列表的存储方式,存储顺序和添加顺序相同
元素可重复
可双向输出
LinkedLisst
LinkedList实现了List接口和Deque接口(继承Queue接口,Queue又继承Collection接口)
Queue接口常用方法【多是操作表头的】:
boolean offer(E e);——添加元素,填加成功返回true,满了添加失败返回false
E remove();——删除head元素,没有时抛异常
E poll();——删除head元素,没有时返回null
E element();——取出head元素,不删除,没有时抛异常
E peak();——取出head元素,不删除,没有时返回null
Deque接口常用方法【多是操作表头或表尾】
void addFirst(E e);
void addLast(E e);
boolean offerFirst(E e);
boolean offerLast(E e);
E removeFirst();
E removeLast();
E pollFirst();
E pollLast();
E getFirst();
E getLast();
E peakFirst();
E peakLast();
LinkedList链表本身是一个实现List接口的集合,和上面学的ArrayList没区别,但是同时又实现了Queue接口里面的抽象方法可以利用Queue和Deque中的抽象方法对链表进行头和尾的操作
Set接口:
Set接口,继承Collection
没有对Collection接口进行扩充,只是不能添加重复的元素
不保证元素顺序,不能双向输出
【HashSet类】实现Set接口:不能存放重复元素,散列存储,存储的数据无顺序
【TreeSet类】实现Set接口:实现了NavigableSet接口——>继承了SortedSet接口——>继承了Set接口;存储的数据有顺序
SortSet接口中的抽象方法:
Comparator<? super E> comparator();
SortedSet<E> subSet(E fromElement, E toElement);
SortedSet<E> headSet(E toElement);
SortedSet<E> tailSet(E fromElement);
E first();
E last();