返回Collection子类型而不是抽象Collection?

时间:2020-10-14 10:59:48

标签: java list collections set

说我有一个(简化的)通用实用程序方法:

public Collection<T> returnExample(Collection<T> col)
{

    return col;
}

如果我给它一个列表,有没有办法让它返回列表而不是集合? 同样,如果我给它一个集合,它如何返回一个集合?

1 个答案:

答案 0 :(得分:0)

public static void main(String[] args) {
    ArrayList<Double> list = returnExample(List.of(1.1, 2.1, 44.2));
    HashSet<String> set = returnExample(Set.of("aaa", "bbb", "ccc"));

    System.out.println(list); // [1.1, 2.1, 44.2]
    System.out.println(set);  // [bbb, aaa, ccc]
}
@SuppressWarnings("unchecked")
public static <U, T extends Collection<U>> T returnExample(Collection<U> col) {
    if (col instanceof Set)
        return (T) new HashSet<U>(col);
    else
        return (T) new ArrayList<U>(col);
}
相关问题