From 9e9405c36ed0fe52986750b90df058831f9be659 Mon Sep 17 00:00:00 2001 From: nickChenyx Date: Wed, 23 Sep 2020 11:17:29 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BA=A4=E5=B9=B6=E9=9B=86=E7=BB=93=E6=9E=9C?= =?UTF-8?q?=E9=9B=86=E5=90=88=E8=AE=BE=E7=BD=AE=E5=88=9D=E5=A7=8B=E5=8C=96?= =?UTF-8?q?=E5=A4=A7=E5=B0=8F=EF=BC=8C=E9=81=BF=E5=85=8D=E6=89=A9=E5=AE=B9?= =?UTF-8?q?=E6=88=90=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cn/hutool/core/collection/CollUtil.java | 34 ++++++++++--------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/hutool-core/src/main/java/cn/hutool/core/collection/CollUtil.java b/hutool-core/src/main/java/cn/hutool/core/collection/CollUtil.java index be05dc667..61c7fc1d0 100644 --- a/hutool-core/src/main/java/cn/hutool/core/collection/CollUtil.java +++ b/hutool-core/src/main/java/cn/hutool/core/collection/CollUtil.java @@ -104,22 +104,22 @@ public class CollUtil { * @return 并集的集合,返回 {@link ArrayList} */ public static Collection union(Collection coll1, Collection coll2) { - final ArrayList list = new ArrayList<>(); if (isEmpty(coll1)) { - list.addAll(coll2); + return new ArrayList<>(coll2); } else if (isEmpty(coll2)) { - list.addAll(coll1); - } else { - final Map map1 = countMap(coll1); - final Map map2 = countMap(coll2); - final Set elts = newHashSet(coll2); - elts.addAll(coll1); - int m; - for (T t : elts) { - m = Math.max(Convert.toInt(map1.get(t), 0), Convert.toInt(map2.get(t), 0)); - for (int i = 0; i < m; i++) { - list.add(t); - } + return new ArrayList<>(coll1); + } + + final ArrayList list = new ArrayList<>(Math.max(coll1.size(), coll2.size())); + final Map map1 = countMap(coll1); + final Map map2 = countMap(coll2); + final Set elts = newHashSet(coll2); + elts.addAll(coll1); + int m; + for (T t : elts) { + m = Math.max(Convert.toInt(map1.get(t), 0), Convert.toInt(map2.get(t), 0)); + for (int i = 0; i < m; i++) { + list.add(t); } } return list; @@ -226,8 +226,8 @@ public class CollUtil { * @return 交集的集合,返回 {@link ArrayList} */ public static Collection intersection(Collection coll1, Collection coll2) { - final ArrayList list = new ArrayList<>(); if (isNotEmpty(coll1) && isNotEmpty(coll2)) { + final ArrayList list = new ArrayList<>(Math.min(coll1.size(), coll2.size())); final Map map1 = countMap(coll1); final Map map2 = countMap(coll2); final Set elts = newHashSet(coll2); @@ -238,8 +238,10 @@ public class CollUtil { list.add(t); } } + return list; } - return list; + + return new ArrayList<>(); } /**