未知类型的数组 [英] Arrays of unknown type

查看:146
本文介绍了未知类型的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么前pression ?[] 非法的?我不明白为什么它比任何更多的犯罪嫌疑人T [] 。我得到有与通用阵列创建问题,让我明白为什么之类的东西新T [] 新?[3] 是不允许的,但我看不出有什么不对?[] 。这将是很好,例如,能够有像无效方法的方法签名(?[] ARR)。这有什么错呢?

Why is the expression ?[] illegal? I don't understand why it is any more suspect than T[]. I get that there are problems with generic array creation, so I see why things like new T[] and new ?[3] are disallowed, but I don't see what's wrong with ?[]. It would be nice, for example, to be able to have a method signature like void method(?[] arr). What's wrong with this?

此外,什么是preferred的方式来写取未知类型的数组的方法?如果您使用

Also, what is the preferred way to write a method taking an array of unknown type? Should you use

public void method(Object[] arr)

在preference到

in preference to

public <T> void method(T[] arr)

或者这是一个例外,通常的规则,应避免在方法签名类型参数,如果该参数类型仅出现一次?

or is this an exception to the usual rule that you should avoid type parameters in method signatures if the type parameter appears only once?

推荐答案

是的,你应该使用

public void method(Object[] arr)

在preference到

in preference to

public <T> void method(T[] arr)

,因为它们都接受相同的一组的潜在参数,第一个是简单的,并具有以下类型参数。

because they both accept the same set of potential arguments, and the first one is simpler and has less type parameters.

为什么前pression ?[] 非法的?

Why is the expression ?[] illegal?

在语法上,因为的左侧[] 必须是实际的类型。语言学上,这是因为它是不必要的,可以使用对象[] 代替。

Syntactically, because the left side of [] must be an actual type. Linguistically, it's because it is unnecessary, you can use Object[] instead.

在一般情况下,当你想要做的事,比如(?延伸X)[] ,在你的心中,只需将其转换为 X [ ] 。同样,只要你想使用类似?扩展X 作为一个独立的类型,认为的X 代替。

In general, whenever you want to do something like (? extends X)[], in your mind, just transform it to X[]. And similarly, whenever you want to use something like ? extends X as a standalone type, think of X instead.

有关泛型类型参数,?延伸X 是必要的,因为泛型不是协变的(列表&LT; A&GT; 不是列表℃的亚型; B&GT; 即使 A B )的一个亚型。然而,数组类型是协变的( A [] 是一个亚型 B [] 如果 A B )的一个亚型,所以有(?延伸X)[] 是不必要的。

For generics type arguments, ? extends X is needed because generic types are not covariant (List<A> is not a subtype of List<B> even if A is a subtype of B). However, array types are covariant (A[] is a subtype of B[] if A is a subtype of B), so having (? extends X)[] is unnecessary.

这篇关于未知类型的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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