我如何返回给定的Collection类型作为参数,但使用不同的元素类型? [英] How can I return the same Collection type given as a parameter, but with a different element type?

查看:414
本文介绍了我如何返回给定的Collection类型作为参数,但使用不同的元素类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这样做:

I want to do this:

public <C extends Collection<?>> C<File> strings_to_files(C<String> strings)
{
    C<File> files = new C<File>();

    for(String string : strings)
    {
        files.add(new File(string)
    }

    return files;
}

我只想让它取任何字符串集合,并返回相同的集合类型有没有办法做到这一点?也许我只是有语法错误...

I just want it to take any Collection of strings, and return that same Collection type with files. Is there any way to do this? Or maybe I just have the syntax wrong...

推荐答案

没有好的我认为最简单的方法就是将目标集合作为第二个参数传递:

There's no good way to do that directly. The easiest thing, I think, would be to pass the target collection as a second argument:

public void string_to_files(Collection<String> strings, Collection<File> files) {
    for(String string : strings) {
        files.add(new File(string));
    }
}

客户端代码可以决定它想要回收哪种类型的集合。做你的问题,但它是避免必须施放和压制警告的最简洁的方法。

The client code can then decide what type of collection it wants back. This doesn't do what you asked, but it's the cleanest way to avoid having to cast and suppress warnings.

或者, t声明返回集合< File> (或特定的集合实现类型)的方法并实例化一个特定的集合您选择的类型。

Alternatively, just declare the method to return a Collection<File> (or a specific Collection implementation type) and instantiate a specific Collection type of your choice.

这篇关于我如何返回给定的Collection类型作为参数,但使用不同的元素类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆