D
D
Drunya20182018-11-04 16:34:59
Java
Drunya2018, 2018-11-04 16:34:59

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

2 answer(s)
E
Elmo Sputterspark, 2018-11-04
@Drunya2018

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 Threadreturned by the call list.get(i).getThread()But you did not add such an object to the list.

A
alfss, 2018-11-04
@alfss

because it appears to be a pointer to a stream object, not an element index in a list or a stream identifier.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question