zack
zack

Reputation: 25

Java arraylist of arraylist - create a multi dimensional arraylist with a class object

I'm looking to create an arraylist of arraylist.

import java.util.ArrayList;
import java.util.List;

class Neighbors{
ArrayList<Integer> inner = new ArrayList();
Neighbors(){}
}

ArrayList<Neighbors> outer = new ArrayList<Neighbors>();

void setup() {
size(1280, 700, JAVA2D);
background(0);

Neighbors test1 = new Neighbors();
Neighbors test2 = new Neighbors();

test1.inner.add(0);
test1.inner.add(1);
test1.inner.add(2);

test2.inner.add(5);
test2.inner.add(6);
test2.inner.add(7);

println(test1.inner);
println(test2.inner);
//  outer.add((ArrayList)test.inner);
outer.add(test1.inner);
outer.add(test2.inner);
println(outer);

}

This is my above code, But I could not add inner arraylist to outer arrays. I'm not sure what I'm doing is right. Or if there is any other method to do this in a right way please help.

Firstly, I'm trying to create an arraylist as objects under a class and i want to use these inner arraylist in outerarraylist. basically i need a 2d arraylist with the help of class. Please advice or help me with a sample code where i can use arraylist within arraylist, add items to it and the way to access them.

Upvotes: 1

Views: 1024

Answers (1)

Dan Zheng
Dan Zheng

Reputation: 1673

Instead of:

outer.add(test1.inner);
outer.add(test2.inner);

Do you want to use the following instead?

outer.add(test1);
outer.add(test2);

Edit: In order to print outer, try this.

First, add a toString() method to the Neighbors class:

class Neighbors {
    ArrayList<Integer> inner = new ArrayList();

    @Override
    public String toString() {
        return inner.toString();
    }
}

Then, you can simply print outer using:

System.out.println(outer);

Alternatively, if you do not want to use a class, you can simply use an ArrayList of an ArrayList:

ArrayList<ArrayList<Integer>> outer = new ArrayList<>();
outer.add(new ArrayList<>());
outer.get(0).add(0);
outer.get(0).add(1);
outer.get(0).add(2);

ArrayList<Integer> inner = new ArrayList<>();
inner.add(3);
inner.add(4);
outer.add(inner);

System.out.println(outer);

This prints out [[0, 1, 2], [3, 4]].

Upvotes: 2

Related Questions