1:泛型 //以后光用个List<String>list=new ArrayList<>();
概念:JDK1.5推出的一种新特性。本质是参数化类型。
ArrayList<String> list=new ArrayList<>(); list.add("a"); list.add("f"); for (String o:list){//这里必须写String不能写除Object别的了 System.out.println(o); }
通配符:public static void addList(List<?> list){}
上下限:
List<A>a=new ArrayList<>(); addList(a); List<B>b=new ArrayList<>(); addList(b); List<C>c=new ArrayList<>(); //addList(c);//这里报错了,因为添加的必须是B的父类 } public static void addList(List<? super B>list){} } class A{} class B extends A{} class C extends B{}
a:泛型的上限:<? extends B> 即 ? 的类型是能是B及其子类
public static void addList(List<? extends B> list){}
b:泛型的下限:<? super B> 即 ?的类型是B及其父类
public static void addList(List<? super B> list){}
2:List
来源:java.util.List interface List exetends Collection
实现类:
ArrayList:底层是数组,有下标。查询快,增删慢
API:
get(int index); 根据下标返回元素
set(int index, E e); 将元素E设置到index位置,原位置的元素返回
add(int index,E e);将元素E插入到index位置,原位置及其后续元素后移
reomve(int index);删除指定位置元素,并将该元素返回
subList(int start, int end); 截取字串,start开始位置,end结束位置
LinkedList:底层是链表,没有下标。查询慢,增删块
3: toArray方法 (集合转换数组)
在Collection中定义了toArray方法,该方法可以将集合转换为数组,所有集合都可用。
形式:
a. Object [] toArray();
b. <T> T[ ] toArray (T[ ] t) ;
当 t数组的长度大于等于 集合的长度时,直接使用。反之,数组扩容。
List<String>name=new ArrayList<>(); name.add("改了"); name.add("大王"); name.add("发我"); name.add("叙述"); String[]arr=name.toArray(new String[]{}); for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); }
4: sort方法 (集合的排序)
Collections & Collection区别
Collection是集合的顶层父类;Collections是集合的工具类。
sort() 就是Collections中的一个工具类,作用是排序!
1:Collection.sort( Collection<E>);
2:Collections.sort(Collection<E> ,Comparator<? super T> c);
比较器可以使用Lambda表达式!
要是排序数字的话sort后啥也不写就行
List<String> list=new ArrayList<>(); list.add("中国"); list.add("撒吊哦啊好的"); list.add("加纳阿瓦达"); list.add("美国的"); System.out.println(list); //此为按字符串长度从大到小排 Collections.sort(list,(o1,o2)->o2.length()-o1.length()); System.out.println(list); //这反过来了,从小到大排 Collections.sort(list,(o1,o2)->o1.length()-o2.length()); System.out.println(list);
5:Queue 队列,他是Linklist的
概念:集合的一种,遵循先进先出的数据结构。
API:
offer:添加元素
pool:删除队首元素,并返回
peek:返回队首元素,并不删除
Queue<String> q=new LinkedList<>(); q.offer("张三"); q.offer("挖的"); q.offer("文档"); q.offer("哇塞"); System.out.println(q); //删除队首元素 String poll=q.poll(); System.out.println(q); String peek=q.peek(); //返回队首元素但不删除 System.out.println(peek); System.out.println(q);
6:Deque
概念:双端队列,即两侧都可以进和出
API:
offer:添加元素
pool:删除队首元素,并返回
Deque e=new LinkedList(); Deque<String>de=new LinkedList<>(); //此为双端队列 e.offer("的"); e.offer("字符"); System.out.println(e);
栈:Stack,即将Deque的一侧堵住,进和出在同一侧,遵循先进后出
API:
push:进栈,添加元素
pop:出栈,删除元素
//此为栈结构,先进后出 de.push("长度"); de.push("噶发"); de.push("a"); System.out.println(de); String p=de.pop(); System.out.println(p);