1 16 package java.util; 17 18 21 public class Collections { 22 23 public static final Set EMPTY_SET = new HashSet (); 24 public static final Map EMPTY_MAP = new HashMap (); 25 public static final List EMPTY_LIST = new ArrayList (); 26 27 45 public static int binarySearch(final List sortedList, final Object key) { 46 return binarySearch(sortedList, key, Comparators.natural()); 47 } 48 49 71 public static int binarySearch(final List sortedList, final Object key, 72 Comparator comparator) { 73 78 comparator = comparator != null ? comparator : Comparators.natural(); 79 int low = 0; 80 int high = sortedList.size() - 1; 81 82 while (low <= high) { 83 final int mid = low + ((high - low) / 2); 84 final Object midVal = sortedList.get(mid); 85 final int compareResult = comparator.compare(midVal, key); 86 87 if (compareResult < 0) { 88 low = mid + 1; 89 } else if (compareResult > 0) { 90 high = mid - 1; 91 } else { 92 return mid; 94 } 95 } 96 return -low - 1; 98 } 99 100 public static void reverse(List l) { 101 int lastPos = l.size() - 1; 102 for (int i = 0; i < l.size() / 2; i++) { 103 Object element = l.get(i); 104 int swapPos = lastPos - i; 105 assert (swapPos > i); 106 Object swappedWith = l.get(swapPos); 107 l.set(i, swappedWith); 108 l.set(swapPos, element); 109 } 110 } 111 112 public static void sort(List target) { 113 Object [] x = target.toArray(); 114 Arrays.sort(x); 115 replaceContents(target, x); 116 } 117 118 public static void sort(List target, Comparator y) { 119 Object [] x = target.toArray(); 120 Arrays.sort(x, y); 121 replaceContents(target, x); 122 } 123 124 private static void replaceContents(List target, Object [] x) { 125 int size = target.size(); 126 assert (x.length == size); 127 for (int i = 0; i < size; i++) { 128 target.set(i, x[i]); 129 } 130 } 131 } 132 | Popular Tags |