2016-03-20 121 views
0

我想要生成客戶對象並將它們存儲在ArrayList中,但我不能。如何通過Java中的線程將項目添加到ArrayList

這裏是我的客戶類

public class Customer { 
private int customerID; 
private int processTime; 

ArrayList<Integer> customerIDList = new ArrayList<>(); 
ArrayList<Integer> processTimeList = new ArrayList<>(); 

public int getCustomerID() { 
    return customerID; 
} 

public void setCustomerID(int customerID) { 
    this.customerID = customerID; 
} 

public int getProcessTime() { 
    return processTime; 
} 

public void setProcessTime(int processTime) { 
    this.processTime = processTime; 
} 

public ArrayList<Integer> getCustomerIDList() { 
    return customerIDList; 
} 

public void setCustomerIDList(ArrayList<Integer> customerIDList) { 
    this.customerIDList = customerIDList; 
} 

public ArrayList<Integer> getProcessTimeList() { 
    return processTimeList; 
} 

public void setProcessTimeList(ArrayList<Integer> processTimeList) { 
    this.processTimeList = processTimeList; 
} 
} 

CustomerThread類,這是產生顧客對象10倍和兩個客戶100之間毫秒

public class CustomerThread extends Thread { 
Customer c = new Customer(); 
Methods method = new Methods(); 

@Override 
public void run() { 

    for(int i = 1; i <= 10; i++) { 
     try { 
      //c.setCustomerID(i); 
      //c.setProcessTime(method.generateProcessTime()); 

      c.getCustomerIDList().add(i); 
      c.getProcessTimeList().add(method.generateProcessTime()); 

      System.out.println("ID : " + c.getCustomerIDList().get(i) + " - Process Time : " + c.getProcessTimeList().get(i)); 
      Thread.sleep(100); 
     } 
     catch (InterruptedException ex) { 
      Logger.getLogger(CustomerThread.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 
} 
} 

generateProcessTime的方法是隨機生成INT數,沒有問題。 這裏是我的測試類

public class Test { 
public static void main(String[] args) { 

    CustomerThread ct = new CustomerThread(); 

    ct.start(); 

} 
} 

當我執行這些,會發生這種錯誤,

異常在線程 「線程0」 java.lang.IndexOutOfBoundsException:指標:1,規格:1

回答

1

您要添加的數字1..10到列表

c.getCustomerIDList().add(i); 

但後來你想在指標1..10

c.getCustomerIDList().get(i) 

檢索數字,但名單是從0索引,這就是爲什麼你IndexOutOfBoundsException
你還是從0..9迭代和增加價值i + 1

for(int i = 0; i < 10; i++) { 
    ... 
    c.getCustomerIDList().add(i + 1); 
    ... 
+0

非常感謝! – MrBoolean

相關問題