views:

189

answers:

2

Hello,
This is probably really simple but I really could not word it properly on Google. See, I have a ArrayList that keeps the info for each thread. Each thread has it's own ID. So, at the beggining:

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 it's 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.
Thanks, Isaac Waller

+3  A: 

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

Pete
I agree. As an example:Hashtable<Integer, ThreadInfo> threads = new Hashtable<Integer, ThreadInfo>// store thread info by idthreads.put(threadId, threadInfo);//get thread info by idthreads.get(threadId); //will be null if no thread with that id
John Ellinwood
Unless you have some esoteric threading concerns that require everything to be synchronized, *never* use Java's Hashtable class. Always use HashMap instead (and you can use a synchronized wrapper if need be).
MetroidFan2002
+9  A: 

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 ) );
banjollity
Since you are using java 1.5 anyway, why not use the auto boxing/unboxing?
Bogdan
Force of habit. Where I work autoboxing is considered harmful and is set to flag an error in the compiler.
banjollity