A Java collection of value pairs? (tuples?)

后端 未结 19 2601
名媛妹妹
名媛妹妹 2020-11-22 05:43

I like how Java has a Map where you can define the types of each entry in the map, for example .

What I\'m looking for is a type

19条回答
  •  滥情空心
    2020-11-22 05:46

    The preferred solution as you've described it is a List of Pairs (i.e. List).

    To accomplish this you would create a Pair class for use in your collection. This is a useful utility class to add to your code base.

    The closest class in the Sun JDK providing functionality similar to a typical Pair class is AbstractMap.SimpleEntry. You could use this class rather than creating your own Pair class, though you would have to live with some awkward restrictions and I think most people would frown on this as not really the intended role of SimpleEntry. For example SimpleEntry has no "setKey()" method and no default constructor, so you may find it too limiting.

    Bear in mind that Collections are designed to contain elements of a single type. Related utility interfaces such as Map are not actually Collections (i.e. Map does not implement the Collection interface). A Pair would not implement the Collection interface either but is obviously a useful class in building larger data structures.

提交回复
热议问题