gpt4 book ai didi

java - 如何从 Java 列表中获取一种类型的所有实例?

转载 作者:行者123 更新时间:2023-11-30 06:30:00 25 4
gpt4 key购买 nike

我的代码中有一些部分看起来像这样:

A, B and C extend D

public ArrayList<A> getA() {
ArrayList<A> allElements = new ArrayList<A>();
for (D el : listOfDs) {
if (el instanceof A) {
allElements.add((A) el);
}
}
return allElements;
}

public ArrayList<B> getB() {
ArrayList<B> allElements = new ArrayList<B>();
for (D el : listOfDs) {
if (el instanceof B) {
allElements.add((B) el);
}
}
return allElements;
}

public ArrayList<C> getC() {
ArrayList<C> allElements = new ArrayList<C>();
for (D el : listOfDs) {
if (el instanceof C) {
allElements.add((C) el);
}
}
return allElements;
}

我想将所有这些组合成一个这样的方法:

public <T> ArrayList<T> get() {
ArrayList<T> allElements = new ArrayList<T>();
for (D el : listOfDs) {
if (el instanceof T) {
allElements.add((T) el);
}
}
return allElements;
}

这在 Java 中可行吗?

此刻我得到

Cannot perform instanceof check against type parameter T. Use instead its erasure Object instead since further generic type information will be erased at runtime

Type safety: Unchecked cast from Node to T

然后我尝试了这个:

@SuppressWarnings("unchecked")
public <T> ArrayList<T> get(Class<T> clazz) {
ArrayList<T> allElements = new ArrayList<T>();
for(D o : listOfDs) {
if (o.getClass() == clazz) {
allElements.add((T) o);
}
}
return allElements;
}

它不会抛出任何错误,但我该如何调用它呢?这没有用:

get(A);

最佳答案

你可以使用 Iterables.filter来自 Guava 。

示例用法:

Iterable<X> xs = Iterables.filter(someIterable, X.class);

由于它是一个开源库,您可以查看源代码以找出您做错了什么。

关于java - 如何从 Java 列表中获取一种类型的所有实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10960144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com