I know how made an arraylist but i dont know how make an arraylist inside an arraylist?

let says:

age is 31

alex and age is gonna be in one arraylist


burren and java is alex dogs;

how can i store burren and java under alex..

The arraylist will have many userinput.

Recommended Answers

All 3 Replies

and why do you assume you need an arraylist for this ?
just create instance variables. this might be an arraylist, but it might just as well be an array, depending on whether or not you know how many dogs alex has.

if you don't know how to create instance variables, don't start using arraylists

Perhaps you should provide the forum with the code you already have, since you know how to make an array, make one and we'll help from there ok?

Well, to answer the question, the usual solution to having a multidimensional ArrayList is to declare an ArrayList of ArrayList of the type being stored:

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

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

However, no experienced Java developer would ever do this. The usual solution is to design a class that holds the personal data for the individual - yes, even if it is a one-off - and have the name, age, and ArrayList of pet's names as instance variables of the class:

class Person {
    public String name;
    public int age;
    public ArrayList<String> pets;

    Person(String name, int age, String ... pets) {
        this.name = name;
        this.age = age;
        this.pets = new ArrayList<String>();
        for (String pet: pets) {

public class myProgram {
    public static void main(String[] args) {
        Person myPerson = new Person("Alex", 31, "Burren", "Java");

I made the fields public for this example to keep it simple, but usually they would be private and give them getters and setters - you wouldn't want uncontrolled access to them, in case someone accidentally changed age to -17, for example.

You'll also note that the c'tor uses a bit of an odd parameter list: the elipsis (the ...) means 'follow this with zero or more arguments of type x before this and put them in an array named y after this'. You don't need to worry too much about it, just know that it will get as many pet names as you want. You can only use this type of parameter (called a variadic parameter) as the last parameter of the parameter list.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.