Question

as per the title I am struggling to find the cause of an "unchecked or unsafe operations" warning in some code.

If I have the following code, it compiles without any warnings:

public void test()
{
     Set<String> mySet = new HashSet<String>();
     Set<String> myNewSet = mySet;
     //do stuff
}

Now, if I change where mySet comes from, specifically as the result of a method call, I get the "unchecked yadda yadda" warning:

public void test()
{
    Set<String> myNewSet = this.getSet();
    //do stuff
}

public Set getSet()
{
    Set<String> set = new HashSet<String>();
    return set;
}

I have tried and tried to work out what the problem is and I am completely stumped. The issue is present whether I use Sets or Lists. Why would the Set returned by the getSet method be any different to the Set in the first example?

Any help would be greatly appreciated as while the warning isn't the end of the world, it is bugging the hell out of me! :(

Regards

Was it helpful?

Solution

You need to declare the method to return the parameterized type.

public Set<String> getSet()
{
    Set<String> set = new HashSet<String>();
    return set;
}

To learn more about Generics, check the Sun tutorial on the subject (PDF).

OTHER TIPS

The solution is to change your method signature from

public Set getSet()

to

public Set<String> getSet()

You are trying to assign a raw Set to a Set<String>, which is inherently unsafe because the former can hold values that the latter can't.

You can also try parameterizing the method, so that it will work with String, Integer, or any other type T.

public Set<String> getSet()  // You need to change the signature to this.
{
    Set<String> set = new HashSet<String>();
    return set;
}

You forgot to declare the return type of your getSet() call properly.

You have:

public Set getSet() {

whereas you want to return a Set<String> like this:

public Set<String> getSet() {

Your method returns Set, not Set<String>, so when you assign Set<String> mySet = Set; That's an unchecked operation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top