삽입 순서를 유지하는 것 외에도 고유 한 요소 집합을 저장하기 위해 LinkedHashSet을 사용하는 기존 기능이 있습니다.LinkedHashSet에서 요소를 검색하는 가장 효율적인 대안은 무엇입니까?
LinkedHashSet에 이미있는 특정 요소를 검색해야하는 새로운 요구 사항이 있습니다. 즉 요소 추가를 시도 할 때 메서드는 요소가 이미 있는지 확인하고 기존 요소를 반환해야합니다. LinkedHashSet에는 최대 10000 개의 요소가있을 수 있습니다. 이를 달성하기
현재 방법은 효율적인 대안 데이터 구조 방법이있는 LinkedHashSet의
Class CustomObject {
String id;
String name;
CustomObject (String id, String name) {
this.id = id;
this.name = name;
}
LinkedHashMap<String, LinkedHashSet<CustomObject>> parentRecord = new LinkedHashMap<String, LinkedHashSet<CustomObject>>(4);
.
.
.
public CustomObject addCustomObject (CustomObject customObject)
//Assume the following child node not to be null
Set<CustomObject> child = parentRecord.get("customObjectName");
if (child.contains(customObject)) {
Iterator<CustomObject> it = child.iterator();
while (it.hasNext()) {
CustomObject node = it.next();
if (node.getId().equals(customObject.getId())) {
return node;
}
}
}
child.add(customObject);
return customObject;
}
}
에 반복자를 사용하는 것입니다 그 것이다
스토어 고유 값
반환 추가하려고 할 때 이미 존재하는 특정 요소
customObject 자체 따라서 반복기로서 갔다 든 그다지 일 sense.However을 만든다 복귀 신청서 (가능한 경우) customObject 집합에 이미 첨가되어 있기 때문에
을 보존 노드 안에 노드를 만들고 있습니다. 반환 된 customObject는 자식 노드를 가질 수 있습니다.
의미 상'Set.contains (object)'가 true를 반환하면 이미 저장된 요소 (또는 이와 동등한 인스턴스) - contains()!의 매개 변수! 따라서 Set에서 특정 요소를 get()하는 것은 의미가 없습니다. Map은 불변의 식별자를 엔티티의 특정 상태 나 인스턴스에 매핑 할 수 있기 때문에 달성하고자하는 것에 더 적합합니다. – Pyranja
(참고 : 위의 코드는 컴파일되지 않습니다 .' return child;'문이 잘못된 유형의 값을 반환합니다. 'return customObject;'여야합니다.) –
잘 잡히고, 지금 코드를 수정했습니다 .-) – GBP