4

Sorry i really dont know how to do this, last resort but to ask. I wanted to add values to the string list. But my code is not working

private List<String> sample = new ArrayList<String>(){"item1","item2","item3"};
2
  • 1
    Agreed, there are at least 10 different examples of doing exactly what he's asking there. Commented Mar 9, 2014 at 13:34
  • I do not see this as duplicate. Nobody seem to notice that question specifies private List<String> and answers stipulate ArrayList<String> which is another thing. So this is not actually even answered properly. But fulfilled the cause.
    – Lj MT
    Commented Aug 12, 2019 at 22:09

2 Answers 2

5

Here it is:

List<String> sample = new ArrayList<String>(Arrays.asList("item1", "item2", "item3"));
2
  • Thank you, both of your answer work, i tried very hard to look for a solution on android developer, but i do not know which page to look for. Commented Mar 9, 2014 at 13:44
  • Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serializable and implements RandomAccess. This method also provides a convenient way to create a fixed-size list initialized to contain several elements: List<String> stooges = Arrays.asList("Larry", "Moe", "Curly"); docs.oracle.com/javase/7/docs/api/java/util/Arrays.html Commented Mar 9, 2014 at 13:46
4

Try,

ArrayList<String> list = new ArrayList<String>() {{
    add("item1");
    add("item2");
    add("item3");
}}

OR

ArrayList<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
list.add("item3");
2
  • Thank you for the solution sir, may i ask why is there double quotes,{{}}. Commented Mar 9, 2014 at 13:49
  • @lonelearner In the first case we are making an anonymous inner class with an instance initializer (double brace initialization) For More : c2.com/cgi/wiki?DoubleBraceInitialization
    – Rakesh KR
    Commented Mar 9, 2014 at 13:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.