[英]java.lang.IndexOutOfBoundsException
我有一個SQL查詢,該查詢返回整數數組。
ArrayList<Integer> intArray = new ArrayList<>(44);
while (result.next()){
intArray.add(result.getInt("CNT")); // Insert the result into Java Array List
}
// Insert the result into Java Object
dc = new DCDataObj(
intArray.get(1), // Datacenter 1000
intArray.get(2), // Zone 1100
..................
)
運行代碼時出現此錯誤: java.lang.IndexOutOfBoundsException: Index: 40, Size: 40
您能告訴我使用ArrayList時我的錯誤在哪里嗎?
您必須從索引0開始而不是1
dc = new DCDataObj(
intArray.get(0), // Datacenter 1000
intArray.get(1), // Zone 1100
代替
dc = new DCDataObj(
intArray.get(1), // Datacenter 1000
intArray.get(2), // Zone 1100
...
采用
dc = new DCDataObj(
intArray.get(0), // Datacenter 1000
intArray.get(1), // Zone 1100
...
由於List
索引從零開始(就像數組和字符串一樣)。
如果我是您,我可能會提供DCDataObj
的構造函數,該構造函數將List<Integer>
作為參數,然后您可以簡單地調用
dc = new DCDataObj(intArray);
另一種方法是使用這樣的方法:
dc = new DCDataObj();
for (Integer k: intArray) {
dc.add(k);
}
然后,您可以動態添加元素。
您試圖獲取只有40個元素的數組列表的第41個元素。
請記住,就像數組(以及Java中的所有索引集合)一樣,索引從0開始。
您應該從以下內容開始:
dc = new DCDataObj(
intArray.get(0), ... , intArray.get(39) ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.