企业网站的seo,使用html5做语音标注网站,网站开发与维护项目招标,大连旅游问题描述
在实际开发中经常会有类似的这种代码#xff0c;想要按类的某一个属性对列表中的元素分组。
例如#xff1a; 有一些学生#xff0c;然后根绝他们的年龄对他们进行分组。可以写出如下代码。
public class UnsupportedOperationExceptionDemo {DataNoArgsConstru…问题描述
在实际开发中经常会有类似的这种代码想要按类的某一个属性对列表中的元素分组。
例如 有一些学生然后根绝他们的年龄对他们进行分组。可以写出如下代码。
public class UnsupportedOperationExceptionDemo {DataNoArgsConstructorAllArgsConstructorpublic static class Student {private String name;private Integer age;}public static void main(String[] args) {// 初始化几个学生ListStudent studentList new ArrayList();studentList.add(new Student(张三, 18));studentList.add(new Student(李四, 19));studentList.add(new Student(王五, 18));studentList.add(new Student(赵六, 20));// 根据年龄对这个分组MapInteger, ListStudent map new HashMap();for (Student student : studentList) {if (map.containsKey(student.getAge())) {ListStudent students map.get(student.getAge());students.add(student);} else {map.put(student.getAge(), Arrays.asList(student));}}}
}运行结果 这是为什么呢
原因分析
在for循环中如果集合中没有这个年龄的学生则需要创建一个List然后将元素加入所以偷了一下懒直接使用了Arrays.asList(student)这样的代码。
问题就出在这一行代码
看一下asList的源码发现也是new ArrayList(a) 不过仔细看一下这个ArrayList的全限定名是java.util.Arrays.ArrayList而不是我们平常使用的java.util.ArrayList
那这两个有何不同为什么会报错 因为上面的代码调用了java.util.Arrays.ArrayList对象的add方法这个类并没有重写add方法所以直接使用父类java.util.AbstractList中的方法而父类的add方法就是会抛出UnsupportedOperationException异常
解决方案
方案一创建java.util.ArrayList对象来存放元素
方案二使用Java 8的Stream流来处理
MapInteger, ListStudent map studentList.stream().collect(Collectors.groupingBy(Student::getAge));