1

Is it possible to take objects like a Vector and make it have multiple generics? I know it's possible when you create a class, but will other classes that come with the normal Java API (like Vectors, Stack, etc.) can have multiple generics?

For example:

Vector<String, Integer> vect = new Vector<String, Integer>();
vect.add("Hello!", 0);

From this, one index would have two values, a String and Integer.

Thanks in advance!!

Mark Hildreth
  • 42,023
  • 11
  • 120
  • 109
Rob Avery IV
  • 3,562
  • 10
  • 48
  • 72
  • Related: [What is the equivalent of the C++ Pair in Java?](http://stackoverflow.com/questions/156275/what-is-the-equivalent-of-the-c-pairl-r-in-java) – Dante May Code Nov 15 '12 at 15:02
  • 1
    http://stackoverflow.com/questions/2670982/using-tuples-in-java – T I Nov 15 '12 at 15:08

3 Answers3

4

I wouldn't use a Vector is you can use a List. In your case you need to use a custom class like

class MyClass {
    String s;
    int i;

    MyClass(String s, int i) {
        this.s = s;
        this.i = i;
    }
}

List<MyClass> list = new ArrayList<MyClass>();
list.add(new MyClass("Hello!", 0));

String s = list.get(0).s;
int i = list.get(0).i;
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
3

Collections, e.g. Vector, can only contain 1 type of object. You are trying to store 2 objects. Create a class called StringIntegerTuple that holds 2 references to the objects you want to store, then declare a Vector and store the composite objects instead.

Although semantically it is likely you want a HashMap

Tom Larkworthy
  • 2,104
  • 1
  • 20
  • 29
  • Creating such a tuple class is imo way overkill. OO should be used if it adds value, not just for the sake of it! http://prog21.dadgum.com/156.html – fgysin Nov 15 '12 at 15:20
1

The Vector class implements a growable array of objects, I think you are looking for map, java.util.Map<key,value>, implementation of map is HashMap<k,v>

Map<Integer,String> map = new HashMap<Integer,String>();
map.put(1,"str");
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103