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).
-
1What problem you are facing? Just add it.Kartic– Kartic2016-06-17 12:09:04 +00:00Commented 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.Kanika– Kanika2016-06-20 11:24:01 +00:00Commented 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.Kanika– Kanika2016-06-20 11:25:46 +00:00Commented Jun 20, 2016 at 11:25
Add a comment
|
2 Answers
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!
1 Comment
Kanika
Thank you @Igoranze sir. It got my code working to quite an extent.
You can use the Map or LinkedHashMap> to store the data in particular order
1 Comment
Kartic
I don't think your answer is relevant to the question.