,이 코드는 당신을 도울 수 있습니다 : 당신이 뭔가 다른 뜻이나 설명이 필요한 경우 알려 주시기 바랍니다
import java.util.ArrayList;
import java.util.List;
public class CommonContainers {
public static void main(String[] args) {
List<Container> containers = new ArrayList<Container>(16);
for(int i=0; i<13; i++) {
containers.add(new Container(i, i));
}
//add a few duplicating ones
containers.add(new Container(1,1));
containers.add(new Container(5,5));
containers.add(new Container(6,6));
List<Container> sublist = new ArrayList<Container>();
for (Container c1 : containers) {
for (Container c2 : containers) {
if(c1 != c2 && c1.equals(c2)) {
sublist.add(c1);
}
}
}
for (Container c : sublist) {
System.out.println(c);
}
}
private static class Container {
private int weight;
private int height;
@Override
public String toString() {
return String.format("Container[w=%d,h=%d]", weight, height);
}
public Container(int weight, int height) {
this.weight = weight;
this.height = height;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + height;
result = prime * result + weight;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Container other = (Container) obj;
if (height != other.height)
return false;
if (weight != other.weight)
return false;
return true;
}
}
}
.
내가 지금까지 가지고있는 코드와 매우 비슷하지만 하위 목록 요소는 높이가 같을 때만 동등한 것으로 간주됩니다. 이제 container.removeAll (subList)을 수행하는 동안 ConcurrentModificationException이 발생합니다. 주요 아이디어는 '마스터 목록'을 반복하고, 하위 목록을 만들고, 마스터 목록에서 하위 목록을 제거하고, 씻어서 씻고, 전체 마스터 목록에서 모든 요소가 없어 질 때까지 반복하고 내가 사용할 수있는 목록의 하위 집합을 갖습니다. 예외에 대한 어떤 생각? – Jason
글쎄, 만약 당신이 엘리먼트를 제거하고있는리스트를 반복한다면 엘리먼트를 다룰 때 엘리먼트를 지우면서 크기를 변경하기 때문에 예외가 발생하는 곳이다. 목록의 반복자 (containers.iterator())를 사용하고 예외를 피하려면 반복자 (it.remove())를 통해 제거를 시도하십시오. –