调整大小的数组 [英] Resizing an Array

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

问题描述

如果这是一个普通的数组,我可以创建一个新的数组,然后做arraycopy,但仿制药不会让我这样做。我想出了迄今为止最好的事情是:

If this were a regular array, I could just create a new array and then do arraycopy, but generics won't let me do that. The best thing I've come up with so far is:

public void resize() {
    T[] tempArray = Arrays.copyOf(myArray,myArray.length*3);
}

它编译,但在运行时,我得到一个空指针异常。任何人都可以解释我做错了吗?

It compiles, but at run time, I get a null pointer exception. Can anyone explain what I'm doing wrong?

推荐答案

您可以使用 Arrays.copyOf(myarray的,myArray.length * 3)来使复印件

我的猜测是, myArray的[0] 为空,因此 myArray的[0] .getClass()投空指针

my guess is that myArray[0] is null so myArray[0].getClass() throws the nullpointer

如果你需要,你可以使用这些组件<的运行时类型href=\"http://download.oracle.com/javase/6/docs/api/java/lang/Class.html#getComponentType%28%29\"><$c$c>myArray.getClass().getComponentType()

if you need the runtime type of the components you can use myArray.getClass().getComponentType()

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

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