3

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"};
lonelearner
  • 1,637
  • 4
  • 14
  • 22
  • 1
    Agreed, there are at least 10 different examples of doing exactly what he's asking there. – Jason Nichols Mar 09 '14 at 13:34
  • I do not see this as duplicate. Nobody seem to notice that question specifies `private List` and answers stipulate `ArrayList` which is another thing. So this is not actually even answered properly. But fulfilled the cause. – ljgww Aug 12 '19 at 22:09

2 Answers2

4

Here it is:

List<String> sample = new ArrayList<String>(Arrays.asList("item1", "item2", "item3"));
wypieprz
  • 7,981
  • 4
  • 43
  • 46
  • 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. – lonelearner Mar 09 '14 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 stooges = Arrays.asList("Larry", "Moe", "Curly"); http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html – lonelearner Mar 09 '14 at 13:46
3

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");
Rakesh KR
  • 6,357
  • 5
  • 40
  • 55
  • Thank you for the solution sir, may i ask why is there double quotes,{{}}. – lonelearner Mar 09 '14 at 13:49
  • @lonelearner In the first case we are making an anonymous inner class with an instance initializer (double brace initialization) For More : http://www.c2.com/cgi/wiki?DoubleBraceInitialization – Rakesh KR Mar 09 '14 at 13:53