2016-03-20 21 views
0

Müşteri nesnesini oluşturmak ve bunları ArrayList'e kaydetmek istiyorum ancak yapamadım. İşte Java'da Konuya Göre ArrayList öğesine öğe ekleme

benim Müşteri sınıftır

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; 
} 
} 
müşteri nesne 10 kez ve iki müşteriler 100 ila oluşturmak olduğunu

CustomerThread sınıf msn

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 yöntemi rastgele int sayılar oluşturmak, orada hiçbir sorun. Dizin: İşte benim Testi sınıfı

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

    CustomerThread ct = new CustomerThread(); 

    ct.start(); 

} 
} 

Bunları yürütmek, bu hata olur, dizisindeki

İstisna "Konu-0" java.lang.IndexOutOfBoundsException 1, Boyutu: 1

cevap

1

listede

c.getCustomerIDList().add(i); 
içine sayılar 1..10 ekliyoruz

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

Ama sonra endeksler 1..10

c.getCustomerIDList().get(i) 

de numaralarını almak için çalışıyoruz Ama listeler 0 den endeksli, yani sen IndexOutOfBoundsException
Sen ziyade 0..9 gelen yineleme ve değer i + 1 eklemek gerekir olsun yüzden

+0

Çok teşekkür ederim! – MrBoolean

İlgili konular