fix:list 为空时,CollUtil.max 抛异常 #I7FCA3 https://gitee.com/dromara/hutool/issues/I7FCA3

This commit is contained in:
javalover123 2023-06-21 22:53:09 +08:00
parent a9932e7415
commit ee320387db
2 changed files with 20 additions and 2 deletions

View File

@ -2884,7 +2884,7 @@ public class CollUtil {
* @since 4.6.5
*/
public static <T extends Comparable<? super T>> T max(Collection<T> coll) {
return Collections.max(coll);
return isEmpty(coll) ? null : Collections.max(coll);
}
/**
@ -2897,7 +2897,7 @@ public class CollUtil {
* @since 4.6.5
*/
public static <T extends Comparable<? super T>> T min(Collection<T> coll) {
return Collections.min(coll);
return isEmpty(coll) ? null : Collections.min(coll);
}
/**

View File

@ -1066,4 +1066,22 @@ public class CollUtilTest {
Assert.assertFalse(CollUtil.allMatch(list, i -> i == 1));
Assert.assertTrue(CollUtil.allMatch(list, i -> i <= 6));
}
@Test
public void maxTest() {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
Assert.assertEquals((Integer) 6, CollUtil.max(list));
}
@Test
public void maxEmptyTest() {
final List<? extends Comparable> emptyList = Collections.emptyList();
Assert.assertNull(CollUtil.max(emptyList));
}
@Test
public void minNullTest() {
Assert.assertNull(CollUtil.max(null));
}
}