user3745249
user3745249

Reputation: 37

How I keep elements of ArrayList in java?

I expect this program to print this result:

[john, smith, 85]

[michol, smith, 65]

[benz, red, 90]

but output of this program is:

[]

[]

[]

please help me to correction that.

package javaapplication12;
import java.util.ArrayList;
public class JavaApplication12 
{
    public static void main(String[] args) 
    {
        String[] l=new String[3];
        l[0]="benz black 85";
        l[1]="BMW red 56";
        l[2]="benz red 90";
        ArrayList<ArrayList<String>> ss = new ArrayList<ArrayList<String>>();
        ArrayList<String> s = new ArrayList<String>();
        for(int j=0; j<3; j++)
        {
                String[] part=l[j].split(" ");
                for(int i=0; i<3; i++)
                    s.add(part[i]);
                ss.add(s);
                s.clear();
        }
        System.out.println(ss.get(0));
        System.out.println(ss.get(1));
        System.out.println(ss.get(2));
    }
}

Upvotes: 0

Views: 963

Answers (1)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

You're using the same ArrayList<String> s to add the data of part[], then add it into ss and clearing it. In the end, it's like you add the same empty ArrayList<String> to ss.

Just declare and initialize ArrayList<String> s inside the first for loop. This will create a new ArraList<String> instance per iteration. Also, there's no need to clear the list.

The code should look like this (commented lines that you should remove):

//ArrayList<String> s = new ArrayList<String>();
for(int j=0; j<3; j++) {
    ArrayList<String> s = new ArrayList<String>();
    String[] part=l[j].split(" ");
    for(int i=0; i<3; i++)
        s.add(part[i]);
    ss.add(s);
    //s.clear();
}

Upvotes: 3

Related Questions