英文:
Java ConcurrentModificationException on List.addAll method without any looping
问题
我遇到了ConcurrentModifcationException异常,在以下代码片段中,根据我阅读的有关错误原因的内容(在迭代器打开的情况下修改某些内容)这是没有道理的:
List<Field> kibanaFields = Arrays.asList(KibanaRow.class.getSuperclass().getDeclaredFields());
kibanaFields.addAll(Arrays.asList(KibanaRow.class.getDeclaredFields()));
发生在第二行。
我不理解这个...即使第一行内部实现了一些迭代器,在它返回的时候应该已经关闭了,然后才会运行第二个方法。
这里的目的是获取字段名称的列表,然后稍后在KibanaRow
的每个字段上添加@JsonProperty
注解的值。
英文:
I have the ConcurrentModifcationException raised, on the following snippet, which does not make sense based on what I read on what causes this error (modifying something you have an open iterator over):
List<Field> kibanaFields = Arrays.asList(KibanaRow.class.getSuperclass().getDeclaredFields());
kibanaFields.addAll(Arrays.asList(KibanaRow.class.getDeclaredFields()));
Second line, is where it happens.
I don't understand this.. even if the first line had some iterator implemented inside, it should have been closed by the time it returns and second method runs.
The purpose here, is to get a list of field names, and later on add the value of @JsonProperty
annotation, on each of the KibanaRow
's fields.
答案1
得分: 1
我不明白 CME 的特定原因。如果您展示给我们堆栈跟踪,我们或许能够找出问题所在...
然而,无论如何,您所尝试的做法将不起作用:
List<Field> kibanaFields
Arrays.asList(KibanaRow.class.getSuperclass().getDeclaredFields());
这会创建一个由数组支持的列表。列表的大小是固定的,不能添加或删除元素。
kibanaFields.addAll(Arrays.asList(KibanaRow.class.getDeclaredFields()));
如果KibanaRow.class.getDeclaredFields()
返回一个非空数组,这将尝试向kibanaFields
添加更多元素。但实际上不能。应该会引发异常。
解决我所识别出的问题的一个方法是将asList
结果的内容复制到一个新的ArrayList
中;例如:
List<Field> kibanaFields = new ArrayList<>(Arrays.asList(...));
英文:
I don't understand the particular reason for a CME. If you showed us the stacktrace we may be able to work it out ....
However what you are trying to do will not work anyway:
List<Field> kibanaFields
Arrays.asList(KibanaRow.class.getSuperclass().getDeclaredFields());
This creates a list backed by an array. The list's size is fixed. Elements cannot be added or removed.
kibanaFields.addAll(Arrays.asList(KibanaRow.class.getDeclaredFields()));
If KibanaRow.class.getDeclaredFields()
returns a non-empty array, then this will attempt to add more elements to kibanaFields
. It can't. An exception should ensue.
One solution to the problem I have identified is to copy the asList
result's contents into a new ArrayList
; e.g.
List<Field> kibanaFields = new ArrayList<>(Arrays.asList(....));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论