Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - making objects with key/value pairs?

I want to make the following types of objects. This is my higher-level desire that I'd like to figure out in Java:

ListObject(key, String): every key corresponds to a String value; key is a string itself

ListObject(key, String[]): every key corresponds to an array of Strings; key is a string itself

ListObject(key, String, String[]): same deal but with two value fields per key.

How would I make (and use!) objects of this type?

Thanks.

like image 481
JDS Avatar asked Aug 05 '11 19:08

JDS


2 Answers

You seem to need some Maps rather than Lists. Check the Javadoc for Map implementations; the most common is HashMap, but there are sorted, concurrent, deterministically iterable implementations etc. available too.

ListObject: every key corresponds to a String value; key is a string itself

Map<String, String>

ListObject: every key corresponds to an array of Strings; key is a string itself

Map<String, String[]>

(or preferably Map<String, List<String>>)

ListObject: same deal but with two value fields per key.

Map<String, UserDefinedClassWithTwoFields>
like image 126
Péter Török Avatar answered Sep 30 '22 18:09

Péter Török


Map<KeyType,ValueType> which is implemented by HashMap<KeyType, ValueType> and TreeMap<KeyType, ValueType>, among others -- HashMap is unordered and TreeMap is ordered.

Other useful Maps are LinkedHashMap which is like HashMap but iterates in insertion order, and com.google.common.collect.Maps in Guava which has a bunch of utility methods, and com.google.common.collect.ImmutableMap which is an immutable map implementation.

For your key corresponding to an array of strings, you might want to look at a Multimap which is a map with multiple values for a given key.

like image 25
Jason S Avatar answered Sep 30 '22 19:09

Jason S