我找不到“未经检查或不安全的操作”的原因Java 中的警告
根据标题,我正在努力寻找某些代码中“未经检查或不安全操作”警告的原因。
如果我有以下代码,它会在没有任何警告的情况下进行编译:
public void test()
{
Set<String> mySet = new HashSet<String>();
Set<String> myNewSet = mySet;
//do stuff
}
现在,如果我更改 mySet 的来源,特别是作为方法调用的结果,我会收到“unchecked yadda yadda”警告
public void test()
{
Set<String> myNewSet = this.getSet();
//do stuff
}
public Set getSet()
{
Set<String> set = new HashSet<String>();
return set;
}
:我已经尝试了很多次来找出问题所在,但我完全被难住了。无论我使用集合还是列表,问题都存在。为什么 getSet 方法返回的 Set 与第一个示例中的 Set 有所不同?
任何帮助将不胜感激,因为虽然警告不是世界末日,但它却让我烦恼不已! :(
问候
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您需要声明返回参数化类型的方法。
要了解有关泛型的更多信息,请查看 有关该主题的 Sun 教程 (PDF) 。
You need to declare the method to return the parameterized type.
To learn more about Generics, check the Sun tutorial on the subject (PDF).
解决方案是将您的方法签名从 更改
为
您正在尝试将原始
Set
分配给Set
,这本质上是不安全的,因为前者可以保存以下值:后者不能。您还可以尝试参数化该方法,以便它可以与
String
、Integer
或任何其他类型T
配合使用。The solution is to change your method signature from
to
You are trying to assign a raw
Set
to aSet<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 typeT
.您忘记正确声明 getSet() 调用的返回类型。
你有:
而你想返回一个像这样的
Set
:You forgot to declare the return type of your getSet() call properly.
You have:
whereas you want to return a
Set<String>
like this:您的方法返回
Set
,而不是Set
,因此当您分配SetmySet = Set;
这是一个未经检查的操作。Your method returns
Set
, notSet<String>
, so when you assignSet<String> mySet = Set;
That's an unchecked operation.