List基础知识
List家族特点:有序可重复

List接口常用方法:

List接口特有迭代
源码LisrIterator继承Iterator
通用方法+特有方法
void add(E e)
添加元素
javaListIterator<String> li = names.listIterator(); while (li.hasNext()){ String name = li.next(); if("lisi".equals(name)){ li.add("李四"); } System.out.println(names);
E hasPrevous()
判断当前光标指向的上一个位置是否存在元素;
javaListIterator<String>li =names.listIterator(); System.out.println("光标当前指向的位置的上一个位置是否有元素:"+ li.hasPrevious()); while(li.hasNext()){ String name = li.next(); System.out.println(name); }
int nextindex()
获取光标指向的那个位置的下标
int previousIndex()
获取光标指向的那个位置的上标
java//int nextIndex();获取光标指向的那个位置的下标 ListIterator<String> li = names.listIterator(); while(li.hasNext()){ String name = li.next(); if("lisi".equals(name)){ // 当前取出的元素是"lisi" System.out.println(li.nextIndex());//2 } //int previousIndex();获取光标指向的那个位置的上一个位置的下标 System.out.println(li.previousIndex());//1 System.out.println(name); }
set(E e)
设置的是光标以上的那个元素
next()源码解析
光标从0下标开始,当执行i.next()方法时,根据源码。光标先下移一位,但是返回取出的元素还为光标上一位的元素。
sort()排序方法
静态方法
使用comparable()指定排队规则
重写comparable接口方法自定义排序规则


sort()源码:
在类user中重写comparable()方法,sort传入user,形参就为 Comparable<User> user = new User(),就调用User中重写的comparable()方法了,就为自定义的排序规则。
java
public static <T> void sort(T[] a, Comparator<? super T> c) {
if (c == null) {
sort(a);
} else {
if (LegacyMergeSort.userRequested)
legacyMergeSort(a, c);
else
TimSort.sort(a, 0, a.length, c, null, 0, 0);
}
}
使用Comparator<T>自定义排队规则
方法1:要自定义一个额外的类实现这个接口


方法2:使用匿名内部类:直接 new 接口
