2

I have a String[] (a string array) that has multiple values at its different indexes. Now I want to add this complete array of strings to a single index of an array list (ArrayList).

3
  • 1
    What problem you are facing? Just add it. Commented Jun 17, 2016 at 12:09
  • The ArrayList wasn't storing all the entered data. It was saving info just on one index and then over riding the inputs onwards. Commented Jun 20, 2016 at 11:24
  • It's working fine now. I have initialised the array list just before the main so it doesn't get initialised every time an input is saved. Thank You @Kartic though. Commented Jun 20, 2016 at 11:25

2 Answers 2

2

Try this:

List<String[]> stringArrayList = new ArrayList<String[]>();
stringArrayList.add(/*your String[]*/);

A complete example:

package nl.testing.startingpoint;

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

public class Main
{
    public static void main(String[] args) {

        String[] stringArrayOne = {"one", "two"};
        String[] stringArrayTwo = {"three", "four"};

        List<String[]> stringArrayList = new ArrayList<String[]>();

        stringArrayList .add(stringArrayOne);
        stringArrayList .add(stringArrayTwo);

        for (String[] objectArray : stringArrayList) {
            for (String object : objectArray) {
                System.out.println(object);
            }
        }
    }
}

The output is:

  • one
  • two
  • three
  • four

This is called using generics. Check the link for more generics example!

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @Igoranze sir. It got my code working to quite an extent.
-2

You can use the Map or LinkedHashMap> to store the data in particular order

1 Comment

I don't think your answer is relevant to the question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.