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.
You seem to need some Map
s rather than List
s. 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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With