MrBoolean
MrBoolean

Reputation: 29

How to add item to ArrayList by Thread in Java

I want to generate customer object and store them in ArrayList, but I could not.

Here is my Customer class

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 class which is generate customer object 10 times and between two customers 100 msec

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);
        }
    }   
} 
}

Method of generateProcessTime is generate random int numbers, there is no problem. Here is my Test class

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

    CustomerThread ct = new CustomerThread();

    ct.start();

}
}

When I execute these, this error will happen,

Exception in thread "Thread-0" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1

Upvotes: 0

Views: 596

Answers (1)

radoh
radoh

Reputation: 4825

You're adding numbers 1..10 into the list

c.getCustomerIDList().add(i);

But then you're trying to retrieve numbers at indexes 1..10

c.getCustomerIDList().get(i)

But lists are indexed from 0, that's why you get IndexOutOfBoundsException
You should rather iterate from 0..9 and add value i + 1:

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

Upvotes: 1

Related Questions