I'm putting 1D Arrays in an Array List
ArrayList<int[]> pairs_ref = new ArrayList();
int[]singlePair_ref = new int [2];
singlePair_ref[0] = 15;
singlePair_ref[1] = 0;
pairs_ref.add(singlePair_ref);
return pairs_ref;
However, an test output on the console only s开发者_C百科hows Zeros, not the correct values
pairs_ref = object_ref.methodFillsArrayListAsShownAbove();
for (int t = 0;t<pairs_ref.size();t++){
int[]array_ref = pairs_ref.get(t);
System.out.println("Live: "+array_ref[0]+" "+array_ref[1]);
}//endfor
this Version brings the same result
int[]array_ref = new int[2];
for (int t = 0;t<pairs_ref.size();
array_ref = pairs_ref.get(t);
System.out.println("Live: "+array_ref[0]+" "+array_ref[1]);
System.out.println(pairs_ref.get(t));}
Why is this? Is it the putting or the getting of the variables of the ArrayList? Thanks in Advance! Daniel
If this is the observed output for you, something else is wrong in your code.
The program below (verbatim copy of the snippets you provided) outputs the expected result:
import java.util.*;
class Test {
public static ArrayList<int[]> methodFillsArrayListAsShownAbove() {
ArrayList<int[]> pairs_ref = new ArrayList();
int[] singlePair_ref = new int[2];
singlePair_ref[0] = 15;
singlePair_ref[1] = 0;
pairs_ref.add(singlePair_ref);
return pairs_ref;
}
public static void main(String[] args) {
List<int[]> pairs_ref = methodFillsArrayListAsShownAbove();
for (int t = 0; t < pairs_ref.size(); t++) {
int[] array_ref = pairs_ref.get(t);
System.out.println("Live: " + array_ref[0] + " " + array_ref[1]);
}// endfor
}
}
Output:
Live: 15 0
Ideone.com demo
Link
Note that as of Java 5 your code can be simplified:
ArrayList<int[]> pairs_ref = new ArrayList<int[]>(); //note the use of generics in the parameter
int[] singlePair_ref = new int [2];
singlePair_ref[0] = 15;
singlePair_ref[1] = 0;
pairs_ref.add(singlePair_ref);
//simplification here
for (int[] arr : pairs_ref){
System.out.println("Live: "+arr[0]+" "+arr[1]);
}
This should work at your system.
精彩评论