0

I have an ArrayList defined as:

ArrayList<String[]> params=new ArrayList<String[]>();

It contains parameters ("name", value) in String Arrays. I would like to insert elements in the ArrayList:

params.add({"param1", param1});

But when I try that I get an error.

What is the simplest way to add String Arrays in ArrayList. Do I have to declare a new array each time?

3
  • {"param1", param1} this is not a string array. Commented Mar 19, 2014 at 21:49
  • 4
    It looks like you really want a Map. Commented Mar 19, 2014 at 21:50
  • Just pointing that when you say name/value you might want to look at the Map interface Commented Mar 19, 2014 at 21:51

3 Answers 3

5

A declaration is the only time you can just use braces, e.g.

String[] test = {"param1", param1};

In all other times, you must use new String[] also.

params.add(new String[] {"param1", param1});
0
1

Make a string with some special sequence. Add it in ArrayList and then split it when you need it. For example:

 ArrayList<String> str_list = new ArrayList<String>();
 String str = "name&&&value";
 // Add str to str_list
 str_list.add(str);

Then fetch it from arraylist and split it using following code:

 String str1 = str_list.get(index); 
 String[] values = str1.split("&&&");

values[0] will be name and values[1] will be value.

-1

You should read up on ArrayLists here

But after initialization you can do this:

 params.add("String");
 params.add(aStringObject);

Your initialization is incorrect as well; If you want a ArrayList of Strings it should be:

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

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.