带有子类的Java Collection :: toArray

时间:2015-10-25 01:28:15

标签: java generics collections toarray subtyping

当您只知道集合的子类型时,有没有办法使用Collection::toArray(T[])方法?

举个例子:

void initList(Collection<? extends AorB> data) {
    JList<? extends AorB> aorb_jlist = new JList<>();
    aorb_jlist.setListData(data.toArray(new T<? extends AorB>[data.size()]));
}

abstract class AorB {}
class A extends AorB {}
class B extends AorB {}

(我只是将T放在那里以供说明,我知道这不会有效)

我对Collection的所有了解都是AorB的子类,但也可能是JList的子类。 <? extends AorB>接受setListData作为其类型,但Collection::toArray方法需要一个数组,而toArray需要输入。

我用<? extends AorB>咆哮了错误的树吗?是否有一种简单有效的方法将此Collection转换为数组而无需手动迭代它?

编辑以回答@PaulBoddington:

您无法将<AorB>更改为void initList(Collection<AorB> data) { JList<AorB> aorb_jlist = new JList<>(); aorb_jlist.setListData(data.toArray(new AorB[data.size()])); } abstract class AorB {} class A extends AorB {} class B extends AorB {} public static void main(String[] args) { LinkedList<A> a_list = new LinkedList<>(); initList(a_list); } ,因为该方法无法获得子类型集合:

示例:

incompatible types: LinkedList<A> cannot be converted to Collection<AorB>

抛出错误:

div.tabContent.hide {
  display: none;
}
nav {
  background: rgba(0, 0, 0, 0);
  height: 80px;
  border-radius: 0px;
}
nav ul {
  width: 50%;
  margin: auto;
}
nav ul li {
  list-style-type: none;
  width: 150px;
  margin-top: 15px;
  float: left;
  border: none;
  text-align: center;
}
li a {
  font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
  text-decoration: none;
  color: #333333;
  border-radius: 0px;
  text-shadow: 0 1px 1px rgba(0, 0, 0, .5);
  line-height: 50px;
  display: block;
  transition: all ease-in-out 250ms;
}
li a:hover {
  background: rgba(255, 255, 255, .2);
  box-shadow: 0 8px 8px -6px #333;
  color: #222222;
  padding: 0px 0px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, .5);
}

1 个答案:

答案 0 :(得分:1)

将集合保留为Collection<? extends AorB>,但将JList设为JList<AorB>

void initList(Collection<? extends AorB> data) {
    JList<AorB> aorb_jlist = new JList<>();
    aorb_jlist.setListData(data.toArray(new AorB[data.size()]));
}