gpt4 book ai didi

java - Java中如何通过线程向ArrayList添加项目

转载 作者:行者123 更新时间:2023-12-01 10:11:01 25 4
gpt4 key购买 nike

我想生成客户对象并将它们存储在 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();

}
}

当我执行这些时,会发生此错误,

Exception in thread "Thread-0" java.lang.IndexOutOfBoundsException: Index: 1, Size: 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);
...

关于java - Java中如何通过线程向ArrayList添加项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36113366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com