Ioanna Katsanou
Ioanna Katsanou

Reputation: 504

How to convert from Set to Set<Serializable> in java?

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

Answers (2)

user4910279
user4910279

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

Andy Turner
Andy Turner

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

Related Questions