0

Hello only have a few hours with Java. (from Python) I am trying to define a multidimensional array and populate it with the "add" method. however, I am seeing some bizarre results:

List<String[]> DrawInstructions = new ArrayList<String[]>();
String[] pair = {"",""};

pair[0]="UW";
pair[1]="100";
DrawInstructions.add(pair); 

pair[0]="UM";
pair[1]="10";
DrawInstructions.add(pair);

pair[0]="UT";
pair[1]="50";
DrawInstructions.add(pair)

I expected DrawInstructions to end up with this:

[("UW,"100"),("UM","10"),("UT","50")]

But instead I am getting:

[("UT","50"),("UT","50"),("UT","50")]

I am sure this is pretty elemental but I cant figure it out, I have searched for a couple of hours. Thank you for any advice.

javanna
  • 59,145
  • 14
  • 144
  • 125
Martin Ansat
  • 49
  • 1
  • 7

3 Answers3

3

Problem is, you're changing the same array over and over — .add() does not create a copy for you. Try the following:

List<String[]> DrawInstructions = null;
String[] pair = {"",""};

pair[0]="UW";
pair[1]="100";
DrawInstructions.add(pair); 

pair = new String[] {"",""};
pair[0]="UM";
pair[1]="10";
DrawInstructions.add(pair);

pair = new String[] {"",""};
pair[0]="UT";
pair[1]="50";
DrawInstructions.add(pair);

or, better then,

List<String[]> drawInstructions = new ArrayList<String[]>();
drawInstructions.add(new String[] {"UW", "100"}); 
drawInstructions.add(new String[] {"UM", "10"});
drawInstructions.add(new String[] {"UT", "50"});

which would be closer to Java naming standards, avoid NPEs, minimize local state, and be arguably more readable.

alf
  • 8,377
  • 24
  • 45
2

You are adding the same array (pair) three times. All you do is changing it's value(content). Remember that java operates on references, not on the copies of the objects.

Try to create pair1, pair2, pair3.

disorder
  • 291
  • 1
  • 7
1

You defined only one String[] pair = {"",""};

You edited the same object 3 times and added that to the list. You could do that:

List<String[]> DrawInstructions = new ArrayList<String[]>();

String[] pair1 = {"",""};
pair1[0]="UW";
pair1[1]="100";
DrawInstructions.add(pair1); 

String[] pair2 = {"",""};
pair2[0]="UW";
pair2[1]="100";
DrawInstructions.add(pair2); 
....
juergen d
  • 201,996
  • 37
  • 293
  • 362