集合体系
Collection接口: 单列集合的顶层接口
List接口: 有序的子接口
Vetor集合(数组结构:单线程,都慢)
ArrayList集合(数组结构:查询快,增删慢),
LinkLIst集合(链表结构:查询慢,增删快)
Set集合: 无序的子接口
TreeSet集合,
HashSet集合(哈希表结构:查询快)
LinkedHashSet
Map 双列集合的顶层接口
HashMap 哈希表存储
LikedHashMap
Collection集合中的共性方法
java.util.Collection接口:子接口: --〉List集合,Set集合
定义的是所有单列集合中的共性方法,所有的单列集合都可以使用的共性方法
共性方法:
public boolean add(E e):把给定的对象中添加元素
public void clear();清空集合中所有的元素
public boolean remove();把给定的对象在当前的集合中删除
public boolean contains();判断当前集合是否包含给定的元素
public boolean isEmpty();判断集合是否为空,为空返回true
pubic int size();返回集合中元素的个数
public Object[] toAaary();把集合中的元素存储到数组中
addALL(Collection c):将参数c中的元素,都添加到调用者集合中
removeAll(Collection c):从调用者集合中,删除那些也存在参数c中的元素
containsAll(Collection c):判断调用者,是否包含参数c中的所有元素
retainAll(Collection c):参数c中有哪些元素,就在调用者中保留那些元素(交集)
Collections工具类:用来对集合进行操作
1.public static<T> boolean addAll(Colection<T> c,T...elements):
往集合中添加c中的所有元素 Collections.addAll(list,"a","b","c");
2.public static void shuffile(List<?> list);
打乱集合顺序 Collections.shuffile(list);
3.public static <T> void sort(List<T> list):
将集合中元素按默认顺序(升序)排列 Collections.sort(list);
4.int binarySearch(List<E> list,E e)
在一个有升序顺序的List集合中,通过二分法查找元素e的索引
5.fill(List<E> list,E e):
将list集合中所有的元素都填为e
6.max,min:
获取集合的最大值,或者最小值
7.reverse(List<E> list):
将参数集合list进行反转
8.swap(List<E> list ,int a ,int b):
将索引a和索引b的元素进行交换
9.synchronizedXXX方法系列:
将一个线程不安全的集合出入方法,返回一个线程安全的集合
注意事项:
sort(List<T> list)使用前提
被排序的集合里面存储的元素,必须实现Comparable接口,重写接口中的comparaTo方法
Comparable接口排序规则:
自己(this)- 参数:升序
参数 - 自己(this):降序
public class Person implements Comparable<Person>{}
@Override
public int comparaTo(Person o){
//return 0;认为元素都是相同的
//自定义比较规则,比较两个人的年龄(this,参数Person)
//o 是已经存在在数组中
return this.getAge - o.getAge//年龄升序
return o.getAge - this.getAge//年龄降序
}
public static <T> void sort(List<T> list,Comparator<? super T>):
将集合中的元素按照指定规则排序
Collection.sort(list,new Comparator<Integer>(){
//重写比较规则
@Override
public int compare(Integer o1,Integer o2){
return o1 - o2;//升序
return o2 - o1;//降序
//return o1.getAge() - o2.getAge() 升序
//int result = o1.getAge() - o2.getAge();
if(result==0){
result = o1.getName().charAt(0) - o2.getName().char(0);
}
return result;
}
});
Arrays.sort(arr, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1.length() != o2.length()) {
return o2.length() - o1.length();
}
return o2.compareTo(o1);//字典排序
}
});
Comparator和Comparable的区别
Comparable:自己(this)和别人(参数)比较,自己需要实现Comparable接口,重写比较的规则comparaTo方法
Comparator:相当于找一个第三个裁判,比较两个
规则:o1 - o2 //升序 o2 - o1//降序