复制Iterator元素给数组并保证数组长度等于Iterator元素个数

来源:互联网 发布:童装代理一手货源淘宝 编辑:程序博客网 时间:2024/05/19 00:15

需求如题,iterator没有size()方法,获取不到元素的个数,所以就想无论你有多少个元素就按你有10个元素来处理,放了10个元素之后发现还有元素没有放入,这时候就想对数组进行扩容并将旧数组复制给新数组。但是扩容之后可能会有很多空位置出现,所以在iterator.hasNext()时我们需要使用临时变量来记录iterator循环了多少次,这个临时变量就是iterator的元素个数,有了这个个数之后就好办了。代码:

private static int[] convertIteratoToList(Iterator<Integer> iterator) {int[] smallResult = new int[10];int i = 0;while (iterator.hasNext()) {int size=smallResult.length;if (i >= size) {// 扩容int[] bigResult = new int[smallResult.length * 2];// 复制result内容到bigResultSystem.arraycopy(smallResult, 0, bigResult, 0, size);smallResult = bigResult;bigResult = null;}smallResult[i++] = iterator.next();}if (i != smallResult.length) {// 去掉数组内的空位置int[] bigResult = new int[i];System.arraycopy(smallResult, 0, bigResult, 0, i);smallResult = bigResult;bigResult = null;}return smallResult;}