扩展数组? [英] Expanding an Array?

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

问题描述

我知道你不能动态扩展普通数组,但这是一种有效的方法吗?

I know you can't dynamically expand a normal array but is this a valid way of doing it?

public int size = 0;    
public String[] OrigArray = new String[size+1]; 

public void expand(){


            String[] tempArray = new String[size+1];    

            tempArray = (String[])OrigArray.clone();

            OrigArray = new String[size+1];

            OrigArray = (String[])tempArray.clone();    

            size++;         

    }

我知道比尝试使用更好的方法一个正常的数组,但我想首先使用普通数组。

I'm aware of much better methods than trying to use a normal array but I'd like to figure this for just using a normal array first.

我的愿望是它开始于 OrigArray 为0 + 1(所以1)和<$ c时$ c> expand()被称为新的 tempArray 的大小与 OrigArray 然后持有 OrigArray ,而再次声明 size + 1 然后将 tempArray 复制回新尺寸的 OrigArray 。这对我来说很有意义,但我一直在走出异常?

My desire is that it starts off with OrigArray being 0+1 (so 1) and when expand() is called the new tempArray is made that is the same size as the OrigArray and this then holds OrigArray while OrigArray is declared again with size+1 then the tempArray is copied back to the newly sized OrigArray. This makes sense to me, but I keep getting out of bound exception?

推荐答案

该方法不会更改OrigArray的值;它所做的就是在其中存储克隆的克隆,所以实际上该值不会改变。

The method does not change the value of OrigArray; all it does is store a clone of a clone in it, so in effect the value isn't changed.

我想你想要的是:

public void expand() {
    String[] newArray = new String[OrigArray.length + 1];
    System.arraycopy(OrigArray, 0, newArray, 0, OrigArray.length);

    //an alternative to using System.arraycopy would be a for-loop:
    // for(int i = 0; i < OrigArray.length; i++)
    //     newArray[i] = OrigArray[i];
    OrigArray = newArray;
}

这会创建一个大小比OrigArray大1的数组,复制内容将OrigArray放入其中并将该数组分配给OrigArray。除非你想记住已经调用了多少次 expand(),否则没有理由让变量 size

This creates an array that has a size 1 greater than OrigArray, copies the content of OrigArray into it and assigns that array to OrigArray. Unless you want to remember how many times expand() has been called, there shouldn't be a reason to have the variable size.

编辑:如果您真正想要的是知道如何明智地实现您要求的功能,您可以使用@ÓscarLópez所说的和使用ArrayList。

If what you really want is to know a way to sensibly implement the functionality you asked for, you can go with what @Óscar López said and use ArrayList.

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

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