简体   繁体   中英

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:

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 .

Resizable-array implementation of the List interface.

Use List for this requirement. You can use a ArrayList<ArrayList> in place of 2-dim array. ArrayList is Resizable-array implementation of the List interface.

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. you can use ArrayList or Vectors.

Using java.util.Arrays class it is possible. Please refer below link for answer.

How to increase string array size automatically or dynamically

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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