How to Create an 2D Arraylist in Java

How to create an 2D ArrayList in java?

I want to create a 2D array that each cell is an ArrayList!

If you want to create a 2D array of ArrayList.Then you can do this :

ArrayList[][] table = new ArrayList[10][10];
table[0][0] = new ArrayList(); // add another ArrayList object to [0,0]
table[0][0].add(); // add object to that ArrayList

Two dimensional array list

You would use

List<List<String>> listOfLists = new ArrayList<List<String>>();

And then when you needed to add a new "row", you'd add the list:

listOfLists.add(new ArrayList<String>());

I've used this mostly when I wanted to hold references to several lists of Point in a GUI so I could draw multiple curves. It works well.

For example:

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;

@SuppressWarnings("serial")
public class DrawStuff extends JPanel {
private static final int PREF_W = 400;
private static final int PREF_H = PREF_W;
private static final Color POINTS_COLOR = Color.red;
private static final Color CURRENT_POINTS_COLOR = Color.blue;
private static final Stroke STROKE = new BasicStroke(4f);
private List<List<Point>> pointsList = new ArrayList<List<Point>>();
private List<Point> currentPointList = null;

public DrawStuff() {
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
addMouseListener(myMouseAdapter);
addMouseMotionListener(myMouseAdapter);
}

@Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(STROKE);
g.setColor(POINTS_COLOR);
for (List<Point> pointList : pointsList) {
if (pointList.size() > 1) {
Point p1 = pointList.get(0);
for (int i = 1; i < pointList.size(); i++) {
Point p2 = pointList.get(i);
int x1 = p1.x;
int y1 = p1.y;
int x2 = p2.x;
int y2 = p2.y;
g.drawLine(x1, y1, x2, y2);
p1 = p2;
}
}
}
g.setColor(CURRENT_POINTS_COLOR);
if (currentPointList != null && currentPointList.size() > 1) {
Point p1 = currentPointList.get(0);
for (int i = 1; i < currentPointList.size(); i++) {
Point p2 = currentPointList.get(i);
int x1 = p1.x;
int y1 = p1.y;
int x2 = p2.x;
int y2 = p2.y;
g.drawLine(x1, y1, x2, y2);
p1 = p2;
}
}
}

private class MyMouseAdapter extends MouseAdapter {
@Override
public void mousePressed(MouseEvent mEvt) {
currentPointList = new ArrayList<Point>();
currentPointList.add(mEvt.getPoint());
repaint();
}

@Override
public void mouseDragged(MouseEvent mEvt) {
currentPointList.add(mEvt.getPoint());
repaint();
}

@Override
public void mouseReleased(MouseEvent mEvt) {
currentPointList.add(mEvt.getPoint());
pointsList.add(currentPointList);
currentPointList = null;
repaint();
}
}

private static void createAndShowGui() {
JFrame frame = new JFrame("DrawStuff");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new DrawStuff());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Java - Filling multidimensional (2d) ArrayList like a 2d array

Unlike arrays, you can't initialize an entire ArrayList directly. You can specify the expected size beforehand (this helps performance when you are using very large lists, so it is a good practice to do it always).

int boardSize = 3;
ArrayList<ArrayList<Character>> board = new ArrayList<ArrayList<Character>>(boardSize);
for (int i = 0; i < boardSize; i++) {
board.add(new ArrayList<Character>(boardSize));
for (int j = 0; j < boardSize; j++){
board.get(i).add('0');
}
}

How to create a Multidimensional ArrayList in Java?

ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();

Depending on your requirements, you might use a Generic class like the one below to make access easier:

import java.util.ArrayList;

class TwoDimentionalArrayList<T> extends ArrayList<ArrayList<T>> {
public void addToInnerArray(int index, T element) {
while (index >= this.size()) {
this.add(new ArrayList<T>());
}
this.get(index).add(element);
}

public void addToInnerArray(int index, int index2, T element) {
while (index >= this.size()) {
this.add(new ArrayList<T>());
}

ArrayList<T> inner = this.get(index);
while (index2 >= inner.size()) {
inner.add(null);
}

inner.set(index2, element);
}
}

2D Array List of different types in Java

Instead of a List use a Map: That can "map" a value to another, and store it in a collection.

Something like this:

Map<String, Room> adjacentRooms = new HashmMap<>();

adjacentRooms.put("north", room);
adjacentRooms.get("east");

You may want to use constants, to make sure the values are "discrete".

It has a drawback, tho: it cannot assign more than 1 value to a key, that is more than 1 Rooms to a direction...

How to convert 2Darray into 2D ArrayList in java?

I would suggest 3 improvements in your code.

  1. use array2D[i].length instead of array2D[1].length.

  2. use eachRecord.add(String.valueOf(array2D[i][j])); instead of eachRecord.add(String.valueOf(array2D[j]));.

array2D[index] returns a total array. array2D[indexRow][indexCol] returns the object at those indexes.


  1. Instead of clear() initiate the eachRecord list inside the loop.

List<String> eachRecord = new ArrayList<String>(); inside the first for loop.

String [][]array2D = {{"A", "B"}, {"C", "D"}, {"E", "F"}};
List<List<String>> arrayList2D = new ArrayList<List<String>>();
for (int i = 0; i < array2D.length; i++) {
List<String> eachRecord = new ArrayList<String>();
for (int j = 0; j < array2D[i].length; j++) {
eachRecord.add(String.valueOf(array2D[i][j]));
}
arrayList2D.add(eachRecord);
}
System.out.println(arrayList2D);//[[A, B], [C, D], [E, F]]

If you want to add whole array you could use Arrays#asList method.

String[][] array2D = { { "A", "B" }, { "C", "D" }, { "E", "F" } };
List<List<String>> arrayList2D = new ArrayList<List<String>>();
for (int i = 0; i < array2D.length; i++) {
List<String> eachRecord = Arrays.asList(array2D[i]);
arrayList2D.add(eachRecord);
}
System.out.println(arrayList2D);


Related Topics



Leave a reply



Submit