views:

77

answers:

6

Hello, 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

+4  A: 

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).

BalusC
A: 

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() {
Steven Schlansker
A: 

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

Affe
+2  A: 

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.

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

Oh dear! I cannot believe I missed that. I am glad you lot are awake! It is past 4am here.

embarrassed silence

What? It is my excuse and I am sticking with it!

Thanks for all the very prompt replies. Saved me a headache! :)

I will tick someone when I work out how!

Peter
You're welcome. However, that's not the way to post comments here. Comments are not answers. Use the `add comment` link to post comments on existing answers, or use the `edit` link below your question to update your question to include progress. As to the voting and accepting answers, have a look in the [faq](http://stackoverflow.com/faq). Good luck!
BalusC
Woops! Forgot about that. Haven't used SO for a long while and lost my old account details. I accepted your answer. Thanks again!
Peter