Question

This is probably really simple but I really could not word it properly on Google. I have an ArrayList that keeps the info for each thread. Each thread has its own ID. So, at the beginning:

myList.add(theIdOfTheThread, new InfoForTheThread()); //Add new thread info at index theIdOfTheThread

And when I want info:

myList.get(myId); //The info for the thread

But, I always get OutOfRangeExceptions whenever a lower thread finishes and removes its entry, etc. So, I am sure there must be a better class to use for this, where I can just put entries in at any index I want, and pull them out at any index I want and they stay.

Was it helpful?

Solution

For that kind of access you should really be using an array, or better, a HashMap. Using a list for this is very inefficient and needlessly complicated. If you ever remove an item from the middle of the list everything will move down, and all the indices above the one you removed will require moving down.

An array of InfoForTheThread won't suffer this, but you'll need to know the size of the array you'll need before you start.

Use a HashMap instead - you can use Integers for the keys, and removal won't result in a resequencing.

HashMap<Integer,InfoForTheThread> myInfos = new HashMap<Integer,InfoForTheThread>( 10 );

Adding, retrieving and removing an entry:

myInfos.put( Integer.valueOf( 4 ), new InfoForTheThread() );
InfoForTheThread infoForFour = myInfos.get( Integer.valueOf( 4 ) );
InfoForTheThread infoForFour = myInfos.remove( Integer.valueOf( 4 ) );

OTHER TIPS

Try a hashtable. you can use the thread id as the key and then insert your info as the values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top