Adding value to List<String> = new ArrayList<String>();

44,022

Solution 1

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");

Solution 2

Here it is:

List<String> sample = new ArrayList<String>(Arrays.asList("item1", "item2", "item3"));
Share:
44,022
lonelearner
Author by

lonelearner

A lonely soul in the world of android, drifting and learning android application development. Lonely soul chronicles are found below: Android Advance Reboot https://www.facebook.com/Android-Advance-Reboot-548612572176807/ Android Noob Reboot https://www.facebook.com/Android-Noob-Reboot-1248769758470969/

Updated on March 10, 2020

Comments

  • lonelearner
    lonelearner about 4 years

    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
    lonelearner about 10 years
    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
    lonelearner about 10 years
    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
  • lonelearner
    lonelearner about 10 years
    Thank you for the solution sir, may i ask why is there double quotes,{{}}.
  • Rakesh KR
    Rakesh KR about 10 years
    @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