0

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));
    }
}
1
  • 2
    You should know that Java works with object references which are passed by value. Commented Jun 16, 2014 at 15:21

1 Answer 1

3

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.