I am trying to make pairs of elements in an array and store them in an ArrayList
(al
variable in below code). Then store those ArrayList
objects in an ArrayList
of ArrayList
(variable finalList
in below code) and then print finalList
.
I am able to get my output if I only use ArrayList
and not finalList
, but I want to know what is going wrong in my code. Why is it not displaying me the proper output?
import java.util.ArrayList;
public class Test {
static int[] arr = {2,4,6,8,10};
static ArrayList<Integer> al = new ArrayList<Integer>();
static ArrayList<ArrayList> finalList = new ArrayList<ArrayList>();
public static void makePairs() {
for(int i = 0; i < arr.length - 1; i++) {
al.clear();
al.add(arr[i]);
for(int j = i + 1; j < arr.length; j++) {
al.add(arr[j]);
// System.out.print(al);
finalList.add(al);
al.remove(1);
}
// System.out.println();
System.out.println(finalList);
finalList.clear();
}
}
public static void main(String[] args) {
makePairs();
}
}
This is the output I am getting.
The output I am expecting is:
[[2,4], [2,6], [2,8], [2,10]]
[[4,6], [4,8], [4,10]]
[[6,8], [6,10]]
[[8,10]]
Please help me resolve my problem.