Java 将 Set<Object> 转换为 Collection<String>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24973624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Set<Object> to Collection<String>
提问by MightyPork
I have a Set<Object>
.
我有一个Set<Object>
.
I need to get a Collection<String>
from it.
我需要从中得到一个Collection<String>
。
I can think of making a for loop to add and cast all the Objects, but that is ugly and probably also slow.
我可以考虑创建一个 for 循环来添加和转换所有对象,但这很丑陋,而且可能也很慢。
@Override
public Collection<String> keys()
{
// props is based on HashMap
Set<String> keys = new HashSet<>();
for (Object o : props.keySet()) {
keys.add((String) o);
}
return keys;
}
What is the right way?
什么是正确的方法?
采纳答案by StriplingWarrior
If you know that all the Object
s inside the HashSet
are strings, you can just cast it:
如果您知道Object
里面的所有sHashSet
都是字符串,则可以将其强制转换:
Collection<String> set = (Collection<String>)(Collection<?>)props.keySet();
Java implements generics with erasure, meaning that the HashSet itself doesn't know at runtime that it's a HashSet<Object>
--it just knows it's a HashSet
, and the compiler is responsible for helping programmers to avoid doing things that would create runtime exceptions. But if you know what you're doing, the compiler won't prevent you from doing this cast.
Java 使用擦除来实现泛型,这意味着 HashSet 本身在运行时并不知道它是 a HashSet<Object>
--它只知道它是 a HashSet
,并且编译器负责帮助程序员避免做会产生运行时异常的事情。但是,如果您知道自己在做什么,编译器就不会阻止您执行此转换。