我设法在我的数组中动态添加一个元素,但不幸的是程序停止了。我怎么能继续呢?谢谢!
...
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.");
...
答案 0 :(得分:2)
List
返回的Arrays.asList
是固定大小。尝试添加它会导致异常。
如果要将动态列表初始化为某些值,请执行以下操作:
List<String> messages = new ArrayList<String>(Arrays.asList("Mary", "Nadia!", "Drake"));
或者更好地使用Google Guava's Lists.newArrayList
List<String> messages = Lists.newArrayList("Mary", "Nadia!", "Drake");
答案 1 :(得分:2)
Arrays.asList()返回固定大小List
,我能想到的最简单的修复是 -
List<String> messages = new ArrayList<String>(
Arrays.asList("Mary", "Nadia!", "Drake")
); // Creates a new (mutable) list.