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

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

问题描述

我正在编写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

在此先感谢您的帮助.

Thanks in advance for help..

推荐答案

没有办法,但是您可以使用

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天全站免登陆