package newFeatures8;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CollectionsDemo {
public static void main(String[] args) {
reverseDemo();
}
public static void reverseDemo(){
List<String> list=new ArrayList<>();
list.add("abcd");//String类本身就是实现了Comparable接口
list.add("kkkkk");
list.add("qq1");
list.add("z");
list.add("zz1");
list.add("zz");
list.add("qq1");
list.add("qq1");
list.add("qq2");
list.sort(null);//Collections.sort(list);
System.out.println("原集合是:"+list);
//Collections.reverse(list);
swap(list);
System.out.println("交换后的集合是:"+list);
}
/**
* @author ljh
* @param nothing
* @return void
* @since 1.2
* @description 在List中前后两两交换元素,相当于reverse反转</br>
* list.set(int index,E element)</br>
* public E set(int index,E element)//返回: 以前位于该指定位置上的元素
*
*/
public static void swap(List<String> list){
int size=list.size();
//折半交换,只需要循环一半即可
int mid=size>>1;//相当于/2
for (int i = 0; i < mid; i++) {
//分解步骤:
//String endElement=list.set(size-1-i, list.get(i));
//list.set(i, endElement);
list.set(i, list.set(size-1-i,list.get(i)));
}
}
}
reverse方法的源码:
@SuppressWarnings({"rawtypes", "unchecked"})
public static void reverse(List<?> list) {
int size = list.size();
if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {
for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--)
swap(list, i, j);//请看下面swap方法
} else {
// instead of using a raw type here, it‘s possible to capture
// the wildcard but it will require a call to a supplementary
// private method
ListIterator fwd = list.listIterator();
ListIterator rev = list.listIterator(size);
for (int i=0, mid=list.size()>>1; i<mid; i++) {
Object tmp = fwd.next();
fwd.set(rev.previous());
rev.set(tmp);
}
}
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static void swap(List<?> list, int i, int j) {
// instead of using a raw type here, it‘s possible to capture
// the wildcard but it will require a call to a supplementary
// private method
final List l = list;
l.set(i, l.set(j, l.get(i)));
}
/**
* Replaces the element at the specified position in this list with
* the specified element.
*
* @param index index of the element to replace
* @param element element to be stored at the specified position
* @return the element previously at the specified position
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E set(int index, E element) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
E oldValue = (E) elementData[index];
elementData[index] = element;
return oldValue;
}