this is my first question here! I am trying to print a formatted grid of numbers. I did it with a 2D array just fine, but when I tried doing it with an array list, I couldn't.
I initialized an array list that takes an arraylist of integers and inputted the values using an array because I didn't know a better way to add a lot of elements (don't you have to add each individually using .add("number here")?) Anyways
Here is the code for the 2D array and the 2D arraylist
public static void print2Darray() {
int[][] array = {{10, 15, 30, 40}, {15, 5, 8, 2}, {20, 2, 4, 2}, {1, 4, 5, 0}};
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
public static void print2DList() {
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
int[][] array = {{10, 15, 30, 40}, {15, 5, 8, 2}, {20, 2, 4, 2}, {1, 4, 5, 0}};
List list2 = Arrays.asList(array);
list.addAll(list2);
System.out.println (list2.get(2)); //this prints the memory address (how can I print the number instead?)
System.out.println(Arrays.deepToString(list2.toArray()));
}
}
If I figure out how to print the line before the last correctly, I can specify loop four times for every line and print the values. But, list2.get()
gets the memory address instead of the value.
Thank you!