List<Integer> list = new ArrayList<Integer>(); // suppose the list is 5 7 2 6 8 1 4java
int[] a = {5, 7, 2, 6, 8, 1, 4};數組
List<Integer> list = new ArrayList<Integer>(Arrays.asList(a));app
package y2017.oct; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Main { private static void printArray(Integer[] a) { StringBuilder sb = new StringBuilder(); sb.append("["); for (int x : a) { sb.append(x + ", "); } sb.delete(sb.length() - 2, sb.length()); sb.append("]"); System.out.println(sb.toString()); } public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); list.add(5); list.add(7); list.add(2); list.add(6); list.add(8); list.add(1); list.add(4); System.out.println(list); Collections.reverse(list); System.out.println(list); Collections.sort(list); System.out.println(list); Collections.sort(list, Collections.reverseOrder()); System.out.println(list); Integer[] a = { 5, 7, 2, 6, 8, 1, 4 }; printArray(a); Arrays.sort(a); printArray(a); // Type mismatch: cannot convert from Comparator<Object> to Integer[] // Arrays.sort(a,Collections.reverseOrder()); //Type mismatch: cannot // convert from Comparator<Object> to Integer[] // Arrays.sort(a. Collections.reverseOrder()); // Only work in Java 1.7 // and above Arrays.sort(a, new MyComparatorA()); printArray(a); } } class MyComparator implements Comparator { @Override public int compare(Object arg0, Object arg1) { int first = ((Integer) arg0).intValue(); int second = ((Integer) arg1).intValue(); if (first > second) { return -1; } else if (first < second) { return 1; } else { return 0; } } } class MyComparatorA implements Comparator<Integer>{ @Override public int compare(Integer o1, Integer o2){ return o2.compareTo(o1); } }
[5, 7, 2, 6, 8, 1, 4] [4, 1, 8, 6, 2, 7, 5] [1, 2, 4, 5, 6, 7, 8] [8, 7, 6, 5, 4, 2, 1] [5, 7, 2, 6, 8, 1, 4] [1, 2, 4, 5, 6, 7, 8] [8, 7, 6, 5, 4, 2, 1]