0

I managed to dynamically add an element in my array, but unfortunately the program stops. How can I continue it? Thank you!

....

List<String> messages = Arrays.asList("Mary", "Nadia!", "Drake");

System.out.println("Enter Costumer's Name:"); 
cust_name =in.next();
if(cust_name .equals("Mary"))
System.out.println("Already a member!");
else if (cust_name .equals("Nadia"))
System.out.println("Already a member!");
else if(cust_name .equals("Drake"))
System.out.println("Already a member!");
else
messages.add(in.next());
System.out.println("Not a member! " + cust_name + " just added.");

....

3
  • When you program stops, it should tell you what went wrong. There will be an exception with description and a stack trace. Please post the errors. Commented Apr 1, 2014 at 19:49
  • stacktrace required, also instead of checking hardcoded for each element you should check if(messages.contains(cust_name)) Commented Apr 1, 2014 at 19:50
  • An alternative to what you're doing here is to use a Set<String> (such as HashSet) to store the name. When you add something to a Set, the value returned is a boolean, which tells you whether the value is actually new - and you could print the appropriate message depending on that value. It will make your code shorter and cleaner. Commented Apr 1, 2014 at 20:05

2 Answers 2

2

Arrays.asList() returns a fixed size List, the easiest fix I can think of is -

List<String> messages = new ArrayList<String>(
    Arrays.asList("Mary", "Nadia!", "Drake")
); // Creates a new (mutable) list.
Sign up to request clarification or add additional context in comments.

Comments

2

The List that Arrays.asList returns is fixed size. Trying to add to it will result in an exception.

If you want a dynamic list initialized to some values then do something like:

List<String> messages = new ArrayList<String>(Arrays.asList("Mary", "Nadia!", "Drake"));

Or better yet use Google Guava's Lists.newArrayList

List<String> messages = Lists.newArrayList("Mary", "Nadia!", "Drake");

2 Comments

Oops answer edited :) , initially it said it returns immutable instance and can't be modified

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.