Home >Java >javaTutorial >How Can I Create an Ordered Collection of Typed Value Pairs in Java Like an Array?

How Can I Create an Ordered Collection of Typed Value Pairs in Java Like an Array?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-15 09:49:09362browse

How Can I Create an Ordered Collection of Typed Value Pairs in Java Like an Array?

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. This class enables you to create individual pairs of values. By creating a List>, you can store an ordered collection of pairs.

To populate the collection, use AbstractMap.SimpleEntry. This allows you to define pairs with specific values:

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn