开发者

I can't find the cause of an "unchecked or unsafe operations" warning in Java

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>();
 开发者_JAVA百科    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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜