Java Collection for Value Pairs: An Array-Like Solution
In Java, you can define collections that hold key-value pairs using Map. However, you seek a collection where each element consists of two values, each with its own type, and that maintains the original order. This effectively resembles an array with specific types for each element.
To fulfill this requirement, consider utilizing java.util.Map.Entry
To populate the collection, use AbstractMap.SimpleEntry
Entry<String, Integer> pair1 = new SimpleEntry<>("Not Unique key1", 1); Entry<String, Integer> pair2 = new SimpleEntry<>("Not Unique key2", 2);
Alternatively, you can subclass ArrayList to encapsulate the creation of pairs and add a convenient of method:
public class TupleList<E extends Map.Entry<K, V>> extends ArrayList<E> { public static <K, V> TupleList<Map.Entry<K, V>> of(K key, V value) { TupleList<Map.Entry<K, V>> list = new TupleList<>(); list.add(new SimpleEntry<>(key, value)); return list; } }
Using this approach, you can define and populate a collection of pairs with specific types:
TupleList<Map.Entry<String, Integer>> pairList = TupleList.of("Not Unique key1", 1); pairList.of("Not Unique key2", 2);
This solution provides an array-like structure with type-safe value pairs, avoiding the verbosity of custom classes or the casting required with 2D arrays.
The above is the detailed content of How Can I Create an Ordered Collection of Typed Value Pairs in Java Like an Array?. For more information, please follow other related articles on the PHP Chinese website!