Lists工具包中的Partition方法踩坑记
由于微服务的性能要求,大部分接口对调用做了数量限制,但是在调用时超过限制数量时,就只有通过分页的方式调用。
对于List比较好的分页方式就是使用Lists工具包中的Partition方法调用,但是今天在使用时,发现接口调用时发生异常。debug发现是subList导致的。subList的实现逻辑就不谈了,往上追溯发现是Partition方式也使用了subList,所以导致问题发生。
public static List> partition(List list, int size) {checkNotNull(list);checkArgument(size > 0);return (list instanceof RandomAccess)? new RandomAccessPartition(list, size): new Partition(list, size);}private static class Partition extends AbstractList> {final List list;final int size;Partition(List list, int size) {this.list = list;this.size = size;}@Overridepublic List get(int index) {checkElementIndex(index, size());int start = index * size;int end = Math.min(start + size, list.size());return list.subList(start, end);}@Overridepublic int size() {return IntMath.divide(list.size(), size, RoundingMode.CEILING);}@Overridepublic boolean isEmpty() {return list.isEmpty();}}
对于这种问题,有两种解决方案:
(1)使用Lists.newArrayList(list)重新建一个list
(2)在接口设计时,参数尽量使用Array,而不是list
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
