Search code examples
javaarraylisttupleskeyvaluepair

Java Tuple/Pair


My Pair class:

public class Pair<o,t> {

      private o one;
      private t two;

      public Pair(o one, t two) {
        this.one = one;
        this.two = two;
      }

      public o getO() { 
          return one;
      }

      public void setO(o one) {
          this.one = one;
      }

      public t getT() {
          return two;
      }

      public void setT(t two) {
          this.two= two;
      }
}

In my main application I fill a list with the pair object:

List<Pair<Integer, String>> test = new ArrayList<Pair<Integer, String>>();
Pair<Integer, String> pair;

pair.setO(1);
pair.setT("A");
test.add(pair);

pair.setO(2);
pair.setT("B");
test.add(pair);

I want to be able to get the integer value only by list index, eg. for-loop to write out A, B, etc. How would I do that? Is there a simpler way of doing such a thing in Java?


Solution

  • As @Braj suggested, you can use a for-each loop.

    for(Pair<Integer, String> p : test ){
        System.out.println(p.getT());
    }
    

    However, because of the way you are adding objects, the output will actually be:

    B
    B
    

    This is because when you add an object to the ArrayList, you are actually adding a reference to that object, so when you modify it, you will modify the one stored in the ArrayList as well. A separate copy of the object is not created! You need to construct a new Pair object for this to work as you intend.

    Another note: you haven't used a constructor to initialize pair, so javac will yell at you.

    To get around both of theses errors, change your code to this:

    List<Pair<Integer, String>> test = new ArrayList<Pair<Integer, String>>();
    test.add(new Pair<Integer, String>(1, "A"));
    test.add(new Pair<Integer, String>(2, "B"));
    for(Pair<Integer, String> p : test ){
        System.out.println(p.getT());
    }