Java 列表允许空白
这可能真的很简单,但我真的无法在谷歌上正确地表达它。 我有一个 ArrayList 来保存每个线程的信息。 每个线程都有自己的ID。 所以,一开始:
myList.add(theIdOfTheThread, new InfoForTheThread()); //Add new thread info at index theIdOfTheThread
当我想要信息时:
myList.get(myId); //The info for the thread
但是,每当较低的线程完成并删除其条目等时,我总是会得到 OutOfRangeExceptions。所以,我确信必须有一个更好的类可以用于此目的,我可以在其中将条目放入我想要的任何索引处,然后将它们拉出我想要的任何索引处,它们会保留下来。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于这种访问,您实际上应该使用数组,或者更好的是 HashMap。 为此使用列表效率非常低并且不必要地复杂。 如果您从列表中间删除一项,所有内容都会向下移动,并且您删除的索引上方的所有索引都需要向下移动。
InfoForTheThread 数组不会遇到这种情况,但在开始之前您需要知道所需数组的大小。
请改用 HashMap - 您可以使用整数作为键,并且删除不会导致重新排序。
添加、检索和删除条目:
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.
Adding, retrieving and removing an entry:
尝试使用哈希表。 您可以使用线程 id 作为键,然后插入您的信息作为值。
Try a hashtable. you can use the thread id as the key and then insert your info as the values.