2016-09-23 2 views

답변

3

은 세트의 복사본을 만듭니다

Set<Serializable> serializableSet = new HashSet<Serializable>(yourSet); 

(당신이 순서를 유지해야하는 경우 LinkedHashSet를 사용).

여기서는 yourSet의 요소가 Serializable을 구현한다고 가정합니다.

+0

Guava가 이미 프로젝트에 존재하는 경우이 배열은 단지 배열 백업이므로 Guava'ImmutableSet'. – chrylis

+0

사본을 만들 때 아무런 요점도 없습니다. 코드는 복사 단계의 유무에 관계없이 유형이 안전하지 않습니다. –

+0

@MarkoTopolnik 우리는 매개 변수로 메서드가 무엇을하는지 알지 못합니다. 집합에 요소를 추가하고 문제를 단순히 제거한 경우 집합이 사용되는 다음 번에 형식 안전 문제가 발생할 수 있습니다. –

1

두 가지 경고가 있습니다. 그러나 그것은 효과적이다. Set<Object>은 다음 anotherMethod((Set)set)를 호출 할 수 있습니다 set하면

void anotherMethod(Set<Serializable> arg) { 
    System.out.println("called"); 
} 

public void myMethod() { 
    Set set = new HashSet<>(); // Set is a raw type. 
           // References to generic type Set<E> 
           // should be parameterized 
    anotherMethod(set); // Type safety: 
         // The expression of type Set needs unchecked 
         // conversion to conform to Set<Serializable> 
} 

이다.

+0

어쩌면 다음과 같이 사용할 수 있습니다 : void anotherMethod (Set arg) – JIV

관련 문제