import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Lambda {
public static void main(String[] args) {
Person[] arr = {
new Person("张三",18),
new Person("李四", 12),
new Person("王五", 16)
};
Person person11 = new Person("abc", 990);
List<Person> arrayList = Arrays.asList(arr);
arrayList.add(person11); //问题在此处
System.out.println(arrayList);
}
}
Arrays.asList()方法返回的是一个Arrays的内部类ArrayList, 而不是java.util.ArrayList. 内部类中没有重写add()方法.
解决办法是重新创建一个集合,把旧的传递进去
package Lambda2;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class Lambda {
public static void main(String[] args) {
Person[] arr = {
new Person("张三",18),
new Person("李四", 12),
new Person("王五", 16)
};
Person person11 = new Person("abc", 990);
List<Person> arrayList = Arrays.asList(arr);
List<Person> arrayList2 = new ArrayList<Person>(arrayList);
arrayList2.add(person11);
System.out.println(arrayList2);
}