2009年1月15日

Collections


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;

public class Main {

public static void main(String[] args) {
List list = new ArrayList(15);
for (int i = 0; i < 15; i++) {
list.add(i);
}

Collections.rotate(list, 3);
System.out.println("rotate(list, 3): " + list);

Collections.reverse(list);
System.out.println("reverse: " + list);

Random rnd = new Random();
Collections.shuffle(list, rnd);
System.out.println("shuffle: " + list);

Comparator c = Collections.reverseOrder();
Collections.sort(list, c);
System.out.println("reverse sort: " + list);

List subList = list.subList(0, 5);
subList.addAll(list.subList(3, 7));
System.out.println("subList: " + subList);

int frequency = Collections.frequency(subList, 10);
System.out.println("frequency(subList, 10): " + frequency);

subList.addAll(Collections.nCopies(5, 11));
System.out.println("subList.addAll(Collections.nCopies(5, 11)): " + subList);

Collections.replaceAll(subList, 11, 1);

System.out.println("replaceAll(subList, 11, 1): " + subList);
Collections.fill(subList, 7);
System.out.println("fill(subList, 7): " + subList);
}

}
/*
rotate(list, 3): [12, 13, 14, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
reverse: [11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 14, 13, 12]
shuffle: [10, 8, 3, 0, 11, 12, 9, 14, 1, 2, 13, 6, 5, 4, 7]
reverse sort: [14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
subList: [14, 13, 12, 11, 10, 11, 10, 9, 8]
frequency(subList, 10): 2
subList.addAll(Collections.nCopies(5, 11)): [14, 13, 12, 11, 10, 11, 10, 9, 8, 11, 11, 11, 11, 11]
replaceAll(subList, 11, 1): [14, 13, 12, 1, 10, 1, 10, 9, 8, 1, 1, 1, 1, 1]
fill(subList, 7): [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7]
*/

沒有留言:

網誌存檔