1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| public void timeoutReminder() { List<String> list = new ArrayList<>();
List<String> list2 = new ArrayList<>(); for (int i = 0; i < 10000000; i++) { Random random = new Random(); list.add(getRandomString(random.nextInt(100))); list2.add(getRandomString(random.nextInt(100))); } StopWatch stopWatch = new StopWatch(); stopWatch.start(); list.containsAll(list2); stopWatch.stop(); System.out.println(stopWatch.getTotalTimeSeconds()); StopWatch stopWatch2 = new StopWatch(); stopWatch2.start(); CollectionUtils.containsAll(list, list2); stopWatch2.stop(); System.out.println(stopWatch2.getTotalTimeSeconds());
} 0.571 17.27
源码 java.util.List#containsAll
public boolean containsAll(Collection<?> c) { Object[] es = getArray(); int len = es.length; for (Object e : c) { if (indexOfRange(e, es, 0, len) < 0) return false; } return true; } private static int indexOfRange(Object o, Object[] es, int from, int to) { if (o == null) { for (int i = from; i < to; i++) if (es[i] == null) return i; } else { for (int i = from; i < to; i++) if (o.equals(es[i])) return i; } return -1; } 源码org.apache.commons.collections4.CollectionUtils#containsAll
public static boolean containsAll(final Collection<?> coll1, final Collection<?> coll2) { if (coll2.isEmpty()) { return true; } else { final Iterator<?> it = coll1.iterator(); final Set<Object> elementsAlreadySeen = new HashSet<Object>(); for (final Object nextElement : coll2) { if (elementsAlreadySeen.contains(nextElement)) { continue; }
boolean foundCurrentElement = false; while (it.hasNext()) { final Object p = it.next(); elementsAlreadySeen.add(p); if (nextElement == null ? p == null : nextElement.equals(p)) { foundCurrentElement = true; break; } }
if (foundCurrentElement) { continue; } else { return false; } } return true; } }
|