views:

298

answers:

5

how can I create an array of tuples in jsp (java) like (a:1, b:2) (c:3, d:4) ... ...

A: 

There's no default pair / n-tuple class in Java; you'd have to roll your own.

tzaman
+2  A: 

Create a tuple class, something like:

class Tuple {
    private Object[] data;
    public Tuple (Object.. members) { this.data = members; }
    public void get(int index) { return data[index]; }
    public int getSize() { ... }
}

Then just create an array of Tuple instances.

Amir Rachum
Is this Java? Why is this so upvoted? "data.size()" on an array? No error checking on out of bounds? Why not use an existing class like `ArrayList`, which implements this behaviour a lot better?
Pindatjuh
@Pindatjuh, Why don't you supply your own answer on this question? It seems you have stuff to share.
Anthony Forloney
@Pindatjuh, I said "something like this". It's a skeleton of the class, just so he'll understand what it supposed to do. It's not been tested or anything.
Amir Rachum
@Pindatjuh, tuples are typically immutable, so this is a relatively good representation...though the constructor really should be `public Tuple` rather than `public void Tuple`
Mark E
@Mark changed, thanks.
Amir Rachum
A: 

If you are dealing with tuples of fixed size, with fixed names of the attributes, define a simple data class of your own, and then define the array of this class.

If on the other hand you want the attribute names to be flexible and determined at runtime, use a Map structure. In your example above, it seems like HashMap<String,Integer> can do the job. You may want to wrap it in order to reduce its functionality, and maybe also add more specific functionality.

Eyal Schneider
+1  A: 

you could use the HashSet class.

Mark
+1  A: 

if you want an arbitrary size tuple, perl hash style, use a Map<K,V> (if you have a fixed type of keys values - your example looks like Map<Character,Integer> would work - otherwise use the raw type). Look up the java collections for more details about the various implementations.

Given those tuples, if you want to stick them in an sequential collection, I'd use a List (again, look up the collections library).

So you end up with

List<Map<K,V>> listOfTuples

if you need something more specific (like, you'll always have x1, x2, x3 in your tuple) consider making the maps be EnumMaps - you can restrict what keys you have, and if you specify a default (or some other constraint during creation) guarantee that something will come out.

Carl