How to Declare a 2D String Arraylist

How do I declare a 2D String arraylist?

You can go with

List<List<String>> ls2d = new ArrayList<List<String>>();
List<String> x = new ArrayList<String>();
x.add("Hello");
x.add("world!");
ls2d.add(x);

System.out.println(Arrays.deepToString(ls2d.toArray()));

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

How to initialize a 2D String ArrayList in Java

You can use something like that if I understand your need:

List<List<String>> list = Arrays.asList(
Arrays.asList("A", "B"),
Arrays.asList("B", "C"),
Arrays.asList("C", "A")
);

EDIT:

List<List<String>> list = new ArrayList<>(Arrays.asList(
new ArrayList<>(Arrays.asList("A", "B")),
new ArrayList<>(Arrays.asList("B", "C")),
new ArrayList<>(Arrays.asList("C", "A"))
));

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();
}
});
}
}

How to create 2D ArrayList and add elements

Here a way easier example :)

Notice that I give a fixed initial length to the constructor of the ArrayList as we already know the length of the array.

List<List<String>> myListOfListOfString = new ArrayList<List<String>>(answers.length);

for(String[] array : answers)
myListOfListOfString.add(Arrays.asList(array));

See documentation for more details.

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);

Adding element in two dimensional ArrayList

myList.get(0).set(1, 17);

maybe?

This assumes a nested ArrayList, i.e.

ArrayList<ArrayList<Integer>> myList;

And to pick on your choice of words: This assigns a value to a specific place in the inner list, it doesn't add one. But so does your code example, as arrays are of a fixed size, so you have to create them in the right size and then assign values to the individual element slots.

If you actually want to add an element, then of course it's .add(17), but that's not what your code did, so I went with the code above.

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);
}
}

Difference between 2d string array and Array list of string

An ArrayList is a class that implements the interface List.
An array as per declared by:String[] variable is a finite-length data-structure in Java.

The main difference in using a 2D ArrayList instead of a normal array is that the length of an ArrayList is not limited. You may add as many elements to an ArrayList as your RAM allows.

On the other hand, String[][] stringData = new String[10][10]; would limit this matrix to 100 elements (10 rows with 10 elements each). If trying to add an element to index 10 (notice the index only goes from 0 to 9) of a 10x10 matrix, the compiler would throw an error.

In general, if you already know how many spaces you will need in your matrix it is recommended that you use an array. Else, ArrayLists are really good.



Related Topics



Leave a reply



Submit