简体   繁体   English

如何在Java中自动增加数组的大小

[英]How to auto increment the size of an array in java

How the array size is auto increment in java program my requirement is "create a 2 dimensional array sno, in the first dimension name, age in the second dimension so if i pass sds, 25 it should be added to the array [0][sds,25] the array should keep incrementing" my code is like this: 数组大小如何在Java程序中自动递增,我的要求是“在第一维名称中创建一个二维数组sno,在第二维中创建年龄,因此如果我通过sds,则应将其添加到数组[0] [25] [ sds,25]数组应保持递增”我的代码是这样的:

void values() throws IOException{for ( int row = i; row < len; row++ ){
            for ( int column = 1; column <= 1; column++ ){
                arrayValues[row][0] = String.valueOf(row+1);
                System.out.print("Enter "+(row+1)+" Name: ");
                String name = br.readLine();
                System.out.print("Enter "+(row+1)+" age: ");
                int age = Integer.parseInt(br.readLine());
                arrayValues[row][column]= name+","+age;
            }
void incrementSize() throws IOException{String[][] newArray = new String[arrayValues.length][];
    System.out.println(newArray.length);
String[][] t = Arrays.copyOf(arrayValues, newArray.length);

After this how can done my code Please help me 在此之后如何完成我的代码请帮助我

I think the perfect bet of your requirement is ArrayList . 我认为您的需求的最佳选择是ArrayList

Resizable-array implementation of the List interface. List接口的可调整大小的数组实现。

Use List for this requirement. 列表用于此要求。 You can use a ArrayList<ArrayList> in place of 2-dim array. 您可以使用ArrayList<ArrayList>代替2维数组。 ArrayList is Resizable-array implementation of the List interface. ArrayListList接口的Resizable-array实现。

An array is a container object that holds a fixed number of values of a single type. 数组是一个包含固定数量的单一类型的容器对象。

You have to create a new array in order to make the size bigger, there is no dynamic way to increase an existing array. 您必须创建一个新数组以增大大小,没有动态方法来增加现有数组。

Here is a way you can create a new array to increase the size. 这是一种可以创建新数组以增加大小的方法。

int[] a = new int[5];
// fill a
int[] b = Arrays.copyOf(a, 10);

Sounds like you are looking a dynamically growing data structure. 听起来您正在寻找一个动态增长的数据结构。 you can use implementation of list interface which is in java collection frame work. 您可以使用java收集框架中的list接口的实现。 you can use ArrayList or Vectors. 您可以使用ArrayList或Vectors。

Using java.util.Arrays class it is possible. 使用java.util.Arrays类是可能的。 Please refer below link for answer. 请参考以下链接以获得答案。

How to increase string array size automatically or dynamically 如何自动或动态增加字符串数组的大小

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM