所以我有一个程序在 Java 7 上运行良好,但在 Java 8 中无法编译并出现错误。所以,我解决了 Java 兼容性问题,我想我找到了原因(或者我找到了吗?http://bugs.java.com/bugdatabase/view_bug.do?bug_id=7144506 ) 。我想知道是否有一种简短有效的方法来复制我的原始代码片段对 Java 8 的作用。这是一个代表这种情况的程序。在我的代码中有一个 setter 方法可以完成填充数组的工作,但我无法控制它的填充方式。
import java.util.List;
import java.util.Arrays;
public class HelloWorld{
public static void main(String []args){
B someObject=new B();
List<A> a = someObject.getA() == null ? Collections.EMPTY_LIST : Arrays.asList(someObject.getA());
for ( A item : a ) {
System.out.println(item.value);
}
}
}
class A{
String value;
public A(String value){
this.value = value;
}
}
class B{
Object[] getA(){
Object arr[]= new Object[4];
arr[0]=new A("hello");
arr[1]=new A("mello");
arr[2]=new A("jello");
arr[3]=new A("cello");
return arr;
}
}
错误当然是:
HelloWorld.java:8: error: incompatible types: bad type in conditional expression
List<A> a = someObject.getA() == null ? Collections.EMPTY_LIST : Arrays.asList(someObject.getA());
^
inference variable T has incompatible bounds
equality constraints: A
lower bounds: Object
where T is a type-variable:
T extends Object declared in method <T>asList(T...)
Note: HelloWorld.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error
我需要一种(最好是一行/优雅的)替代方法,它也能有效地完成同样的任务。
编辑:澄清。我无法控制 B 类返回给我的内容。我也不能以任何方式修改 A 类(我认为这在任何情况下都无济于事)。我只能控制 HelloWorld 做什么。
最佳答案
如果您无法访问 B,但确定您获得了 A,您可以尝试这样的操作:
Object[] objArray = someObject.getA(); // omit calling getA() twice
List<A> a = objArray == null ? Collections.emptyList() :
Stream.of(objArray)
.map(o -> (A) o) // or place your transform function in here
.collect(Collectors.toList());
正如@JBNizet 所指出的:最简单但不安全因此不推荐的解决方案是只添加一个List
-cast:
List<A> a = objArray == null ? Collections.emptyList() : (List)Arrays.asList(objArray);
如果您不确定数组中的内容,您应该使用以下方法仅过滤掉 A:
List<A> a = objArray == null ? Collections.emptyList() :
Stream.of(objArray)
.filter(o -> o instanceof A)
.map(o -> (A) o) // or place your transform function in here
.collect(Collectors.toList());
或与方法引用相同:
List<A> a = objArray == null ? Collections.emptyList() :
Stream.of(objArray)
.filter(A.class::isInstance)
.map(A.class::cast) // or place your transform function in here
.collect(Collectors.toList());
编辑:添加 objArray
以省略调用 getA()
两次,如@Holger 的回答所示。调用它两次可能比所有其他建议的解决方案更昂贵。
关于Java 8 兼容性问题 : How to convert Object array to Subtype List in Java 8?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40545585/