I like how Java has a Map where you can define the types of each entry in the map, for example <String, Integer>
.
What I'm looking for is a type of collection where each element in the collection is a pair of values. Each value in the pair can have its own type (like the String and Integer example above), which is defined at declaration time.
The collection will maintain its given order and will not treat one of the values as a unique key (as in a map).
Essentially I want to be able to define an ARRAY of type <String,Integer>
or any other 2 types.
I realize that I can make a class with nothing but the 2 variables in it, but that seems overly verbose.
I also realize that I could use a 2D array, but because of the different types I need to use, I'd have to make them arrays of OBJECT, and then I'd have to cast all the time.
I only need to store pairs in the collection, so I only need two values per entry. Does something like this exist without going the class route? Thanks!
Apache Crunch also has a
Pair
class: http://crunch.apache.org/apidocs/0.5.0/org/apache/crunch/Pair.htmlThe Pair class is one of those "gimme" generics examples that is easy enough to write on your own. For example, off the top of my head:
And yes, this exists in multiple places on the Net, with varying degrees of completeness and feature. (My example above is intended to be immutable.)
You could write a generic Pair<A, B> class and use this in an array or list. Yes, you have to write a class, but you can reuse the same class for all types, so you only have to do it once.
I was going to ask if you would not want to just use a
List<Pair<T, U>>
? but then, of course, the JDK doesn't have a Pair<> class. But a quick Google found one on both Wikipedia, and forums.sun.com. Cheersjust create a class like
then create List of this objects of tuples
so you can also implement other new data structures in the same way.
Map.Entry
These built-in classes are an option, too. Both implement the
Map.Entry
interface.AbstractMap.SimpleEntry
AbstractMap.SimpleImmutableEntry