ID的ArrayList的用户定义索引(User Defined Index for an ArrayList of IDs)

我正处于(在Java中)我需要定义生成的id的arraylist的情况。 我不知道在任何给定时间会生成多少,但我知道当生成一个时,生成它的用户需要设置自定义索引,并能够通过该索引检索它。 存储和使用这样的数据结构的普遍接受的标准方法是什么? 数组的arraylist?

I'm in a situation where (in Java) I need to define an arraylist of generated ids. I don't know how many would be generated at any given time, but I do know that when one is generated, the user who generated it would need to set a custom index, and be able to retrieve it by that index. What would be the generally accepted standard way of storing and working with a data structure like this? An arraylist of arrays?

最满意答案

听起来像Map的用例,你可以使用ID作为键和值(或者可能是一个值数组,如果多个值可以具有相同的id)作为值。 然后,您可以使用密钥索引到地图并检索数据。 好处是,即使您想要将ID从int更改为String或甚至其他想法,这仍然有效。

使用像这样的List的问题是,如果我有两个ID 1和3000,那么有2998个浪费的索引,这不是完全理想的。

Sounds like a use case for a Map which you can use the ID as the key and a value (or potentially an array of values, if multiple values can have the same id) as the value. You can then index into the map and retrieve data using the key. The benefit is that this works even if you want to change the ID from an int to a String or even some other idea.

The problem with using a List like this is if I have two ids 1 and 3000 then there are 2998 indices that are wasted, which is not exactly ideal.

更多推荐