0

在java中,按索引获取和设置项目的最佳数据结构是什么?

我最初使用的是 ArrayList,但问题是有时,我需要插入一个大于 arraylist 大小的元素,例如:

pseudocode
array = new ArrayList();
array.set(10, object);

显然这会返回一个错误。我可以用标记值初始化数组,但是使用:

array.size()

总是会说我的数组被填满了。显然它只是充满了哨兵值。

4

2 回答 2

3

If you always know the index at which you're inserting the value, then using a concrete implementation of the Map interface is usually the way to go.

The advantage of this set of classes is that, with knowledge of the index (or the Key in this context), you can directly retrieve the object from memory in O(1) time. That means no searching.

For example:

Map<String, String> map = new HashMap<String, String>();

map.put("KEY", "VALUE");

String key = "KEY";

// Do some processing..

String value = map.get(key);

// value variable now contains "VALUE".

Have a look at the documentation to get a really solid grasp of how to use this set of classes.

于 2013-11-11T09:07:59.483 回答
0

这取决于(经常......)。当您的索引在某个合理范围内并且您将使用几乎所有索引时,请使用适当大小的数组:

Object[] items = new Object[MAX_INDEX];

如果您的范围更大并且您的许多阵列插槽将不会被使用,Map那么您可能需要 a (如其他答案中所述)。HashMap是一种可能的实现:

Map<Integer, Object> items = new HashMap<Integer, Object>();
于 2013-11-11T09:11:43.270 回答