Looly 6 years ago
parent
commit
6a9feb0576
2 changed files with 4 additions and 2 deletions
  1. 1 0
      CHANGELOG.md
  2. 3 2
      hutool-core/src/main/java/cn/hutool/core/util/RandomUtil.java

+ 1 - 0
CHANGELOG.md

@@ -23,6 +23,7 @@
 ### Bug修复
 * 【core】         修复NetUtil.getUsableLocalPort问题(pr#69@Gitee)
 * 【core】         修复MathUtil.arrangementSelect重复元素导致无结果问题(issue#529@Gitee)
+* 【core】         修复RandomUtil.randomEleSet越界问题(issue#535@Gitee)
 
 -------------------------------------------------------------------------------------------------------------
 

+ 3 - 2
hutool-core/src/main/java/cn/hutool/core/util/RandomUtil.java

@@ -14,6 +14,7 @@ import java.util.Random;
 import java.util.Set;
 import java.util.concurrent.ThreadLocalRandom;
 
+import cn.hutool.core.collection.CollUtil;
 import cn.hutool.core.date.DateField;
 import cn.hutool.core.date.DateTime;
 import cn.hutool.core.date.DateUtil;
@@ -355,13 +356,13 @@ public class RandomUtil {
 	 * @throws IllegalArgumentException 需要的长度大于给定集合非重复总数
 	 */
 	public static <T> Set<T> randomEleSet(Collection<T> collection, int count) {
-		ArrayList<T> source = new ArrayList<>(new HashSet<>(collection));
+		final ArrayList<T> source = CollUtil.distinct(collection);
 		if (count > source.size()) {
 			throw new IllegalArgumentException("Count is larger than collection distinct size !");
 		}
 
 		final HashSet<T> result = new HashSet<T>(count);
-		int limit = collection.size();
+		int limit = source.size();
 		while (result.size() < count) {
 			result.add(randomEle(source, limit));
 		}