diff --git a/hutool-core/src/main/java/cn/hutool/core/util/ObjectUtil.java b/hutool-core/src/main/java/cn/hutool/core/util/ObjectUtil.java
index e49cc85f53..8f08980aa6 100644
--- a/hutool-core/src/main/java/cn/hutool/core/util/ObjectUtil.java
+++ b/hutool-core/src/main/java/cn/hutool/core/util/ObjectUtil.java
@@ -72,14 +72,14 @@ public class ObjectUtil {
}
/**
- * 计算对象长度,如果是字符串调用其length函数,集合类调用其size函数,数组调用其length属性,其他可遍历对象遍历计算长度
- * 支持的类型包括:
+ *
计算对象长度,支持类型包括:
*
- * - CharSequence
- * - Map
- * - Iterator
- * - Enumeration
- * - Array
+ * - {@code null}:默认返回{@code 0};
+ * - 数组:返回数组长度;
+ * - {@link CharSequence}:返回{@link CharSequence#length()};
+ * - {@link Collection}:返回{@link Collection#size()};
+ * - {@link Iterator}或{@link Iterable}:可迭代的元素数量;副作用:{@link Iterator}只能被迭代一次
+ * - {@link Enumeration}:返回可迭代的元素数量;副作用:{@link Enumeration}只能被迭代一次
*
*
* @param obj 被计算长度的对象
diff --git a/hutool-core/src/test/java/cn/hutool/core/util/ObjectUtilTest.java b/hutool-core/src/test/java/cn/hutool/core/util/ObjectUtilTest.java
index 1fd750e381..91a8418870 100644
--- a/hutool-core/src/test/java/cn/hutool/core/util/ObjectUtilTest.java
+++ b/hutool-core/src/test/java/cn/hutool/core/util/ObjectUtilTest.java
@@ -4,13 +4,12 @@ import cn.hutool.core.clone.CloneSupport;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
-import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.time.Instant;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
+import java.util.*;
+
+import static org.junit.jupiter.api.Assertions.*;
public class ObjectUtilTest {
@@ -108,4 +107,32 @@ public class ObjectUtilTest {
String a = null;
assertFalse(ObjectUtil.isNotNull(a));
}
+
+ @Test
+ public void testLengthConsumesIterator() {
+ List list = Arrays.asList("a", "b", "c");
+ Iterator iterator = list.iterator();
+ // 迭代器第一次调用length
+ int length1 = ObjectUtil.length(iterator);
+ assertEquals(3, length1);
+ // 迭代器第二次调用length - 迭代器已经被消耗,返回0
+ int length2 = ObjectUtil.length(iterator);
+ assertEquals(0, length2); // 但当前实现会重新遍历,但iterator已经没有元素了
+ // 尝试使用迭代器 - 已经无法使用
+ assertFalse(iterator.hasNext());
+ }
+
+ @Test
+ public void testLengthConsumesEnumeration() {
+ Vector vector = new Vector<>(Arrays.asList("a", "b", "c"));
+ Enumeration enumeration = vector.elements();
+ // 第一次调用length
+ int length1 = ObjectUtil.length(enumeration);
+ assertEquals(3, length1);
+ // 第二次调用length - 枚举已经被消耗
+ int length2 = ObjectUtil.length(enumeration);
+ assertEquals(0, length2);
+ // 枚举已经无法使用
+ assertFalse(enumeration.hasMoreElements());
+ }
}