Answer the question
In order to leave comments, you need to log in
Java. Why not the correct Leaf index?
When displaying the name of the current thread - everything happens correctly. And when I print the index of the same stream, I get -1. What am I doing wrong?
int countOfShips = scanner.nextInt();
List<MyOwnThread> list = new ArrayList<>();
Runnable runnable = new Runnable() {
@Override
public void run() {
int randomIndex = (int) (Math.random() * ((countOfShips-1) - 0)) + 0;
while (randomIndex == list.indexOf(Thread.currentThread())){
randomIndex = (int) (Math.random() * ((countOfShips-1) - 0)) + 0;
}
System.out.println(Thread.currentThread().getName());
System.out.println(list.indexOf(Thread.currentThread()));
}
};
for (int i = 0; i < countOfShips; i++) {
list.add(i, new MyOwnThread());
list.get(i).setHp(random.nextInt(51) + 50);
list.get(i).setDamage(random.nextInt(11) + 20);
list.get(i).setCoolDown(0.2f + random.nextDouble() * 1.5f);
Thread thread = new Thread(runnable);
list.get(i).setThread(thread);
list.get(i).getThread().start();
list.get(i).getThread().join();
}
Answer the question
In order to leave comments, you need to log in
List.indexOf()
returns -1 when it cannot find the argument passed to it in the list. In your example, the argument List.indexOf()
is the class object Thread
returned by the call list.get(i).getThread()
But you did not add such an object to the list.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question