如何在运行时根据用户/程序员的需要自动增加数组的大小? [英] How can I increase size of array automatically as per user/programmer need at run time?

查看:12
本文介绍了如何在运行时根据用户/程序员的需要自动增加数组的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写 Java 的 Vector 类和所有其他 Java 集合类的代码,但是我遇到了一个问题,即如何在运行时自动增加数组的大小.并且程序正常运行而不会给出数组越界异常"..嗯,这是我的代码

I am writing code of Vector class of java and all other collection classes of Java but i am having problem that how it is possible to do that the size of array increase automatically at run time.. and program run properly without giving "Array out of bound Exception" .. Well,This is my code

预先感谢您的帮助..

推荐答案

没有办法,但是可以使用LinkedList 或实现您自己的解决方案(Ziakad 在评论部分说这应该放入 Vector 类时是对的.我只是给出一般描述,但在问题的上下文中,这是一个很好的建议):

There is no way to do so, but you can use LinkedList or implement your own solution (Ziakad was right in the comment section when he stated this should be put into the Vector class. I was just giving a general description, but in the context of the question this is a good suggestion):

public static int[] raiseSize(int[] input, int newSize) {
    int[] output = new int[newSize];
    for (int i = 0; i < input.length; i++) output[i] = input[i];
    return output;
}

使用示例:

int foo[] = new int[3];
foo[0] = 1; foo[1] = 2; foo[2] = 0;
foo = raiseSize(foo, 5);

这篇关于如何在运行时根据用户/程序员的需要自动增加数组的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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