1

If I want to define a list of strings containing three items "Larry", "Curly" and "Moe"; and then later on I want to add "Shemp" to this list, is there any way to do this, which does not involve the use of 4 separate adds? What's the best way to complete this operation?

Edited for clarification: I'm using this list of 4 items as an example. In my actual program I need to create a much larger list (hence, why I am looking for a less cumbersome method). And the primary objective is that I would like to define some of the elements of the list right in when I am initializing it, but I also need to add a few elements to the list later on in the code.

1
  • 1
    Use ArrayList with add method. Commented Nov 25, 2013 at 10:33

4 Answers 4

4

You can try this. But what is the issue with use of four add?

    List<String> list=new ArrayList<>();
    list.addAll(Arrays.asList("Larry","Curly","Moe","Shemp"));
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry, I need to add items to my list later on in the code, not all 4 at once)
2

I want to define a list of strings containing three items "Larry","Curly" and "Moe" [....] is there any way to do this, which does not involve the use of 4 separate adds ?

You can use the constructor ArrayList(Collection<? extends E> c)

List<String> list = new ArrayList<>(Arrays.asList("Larry","Curly","Moe"));

and then later on I want to add "Shemp" to this list

Use the add method :

list.add("Shemp");

Comments

1

Define a list:

List<String> list = new ArrayList<String>(
    Arrays.asList("Larry", "Curly", "Moe"));

then when you later want to add "Shemp" do:

list.add("Shemp");

Comments

0
List<String> myList= new ArrayList<String>(Arrays.asList("Larry","Curly", "Shemp", "Moe"));

Comments

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.