Question

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

....

Was it helpful?

Solution

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.

OTHER TIPS

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");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top