开发者

Get ArrayList element by custom text indexing

开发者 https://www.devze.com 2023-01-23 22:23 出处:网络
What I\'m doing is storing classes into an ArrayList and retrieve them by its index number.But are there any list classes in Java where I can retrieve a list element by, lets say, its name?Like this:

What I'm doing is storing classes into an ArrayList and retrieve them by its index number. But are there any list classes in Java where I can retrieve a list element by, lets say, its name? Like this:

ArrayList<st开发者_如何学编程ring> myArr = new ArrayList<string>();
myArr.add( "ID_name", "String to store" );

ands then retrieve it by:

myArr.get( "ID_name" );

Also, are there any other alternatives to ArrayList? I need a list class to be optimized for:

  • Random access
  • Only need to push items into the list
  • Never need to delete anything from the list


If all you want to store is key-value pairs, and don't care about iteration order, I think you might like the HashMap class:

Map<String, String> map = new HashMap<String, String>();
map.put("foo", "bar");
String bar = map.get("foo"); // bar is "bar"


You can use LinkedHashMap, so it will preserve the order, but you can extract elements by key as in regular map. Though you won't be able to extract entries by index.


An ArrayList is just that: an array. If you want to access values by something else than their indices, look for the various implementations of the Map interface (such as HashMap).


Use a Map<String, String>. In such structure, an element is added with a key. So you can get the element through the key:

Map<String, String> map = new HashMap<String, String>();
map.put("id", "string");
String s = map.get("id"); // s will be equals to "string".


As the other people have mentioned, a HashMap is probably what you want if you don't care about iteration order.

If you do, you can use a LinkedHashMap, which is really a HashMap bolted onto an LinkedList, giving you the best of both worlds: fast random access and preservation of iteration order.


Use a hashmap. You can add elements to a hashmap in much the same way as an arraylist. Also, you can create a set of keys ( 1 elements in the set per (key, value) pair)). You can then iterate over the set of keys.

0

精彩评论

暂无评论...
验证码 换一张
取 消