Reputation: 504
I have a Set which I need to use in another method, but this method takes as an input a Set<Serializable>
.
Which is the best way to do this? Any suggestions acceptable.
Upvotes: 0
Views: 819
Reputation:
There are two warnings. But it works.
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>
}
If set
is a Set<Object>
then you can call anotherMethod((Set)set)
.
Upvotes: 1
Reputation: 140514
Make a copy of your set:
Set<Serializable> serializableSet = new HashSet<Serializable>(yourSet);
(use LinkedHashSet
if you need to preserve order).
This assumes that the elements of yourSet
implement Serializable
, of course.
Upvotes: 3