複製Iterator元素給數組並保證數組長度等於Iterator元素個數

需求如題,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內容到bigResult
				System.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;
	}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章