Home  >  Article  >  Computer Tutorials  >  Methods to implement dynamic expansion of arrays in Java

Methods to implement dynamic expansion of arrays in Java

WBOY
WBOYforward
2024-01-12 16:51:161057browse

Methods to implement dynamic expansion of arrays in Java

How to add elements to an array by creating a method in java. The array is full

Reference example:

public class shuzucharu1 {

public static void main(String args[]){

int[] P={1,2,2,47,568,86};

int[] SB=new int[P.length 1];//The array length of SB is 7

int SB1=9;

SB[SB.length-1]=SB1;//When the following table in the SB array is 6, the value is 9

for(int i=0;i

SB[i]=P[i];

System.out.println(SB[i]);

}

System.out.println(SB[SB.length-1]);

}

}//First use the copy algorithm to copy the 6 numbers in the P array to SB. Because the length of the SB array is 7, the seventh number is the subscript 6, and it can be output directly outside the loop.

Insert an element into the sorted array

What type of numbers are in your array? Give an example of int type

import java.util.Arrays;

public class ArySort {

public static void main(String[] args) {

int[] ary = {1, 3, 5,7,9,11};

int[] ary2 = new int[ary.length 1];

System.arraycopy(ary, 0, ary2, 0, ary.length);

ary2[ary.length] = 6;

Arrays.sort(ary2);

for(int value: ary2){

System.out.print(value " ");

}

}

}

--------------

1 3 5 6 7 9 11

How to add an element to the head and tail of the data group in Java

java ArrayList uses add to insert an element. The example is as follows:

import java.util.ArrayList;

public class Test {

public static void main(String[] args) {

ArrayList list = new ArrayList();

list.add(0); //Insert the first element

list.add(1);

list.add(2);

list.add(3);

list.add(4);

list.add(5);

System.out.println(list); //Print list array

list.add(2, 7);

System.out.println(list);

}

}

The above is the detailed content of Methods to implement dynamic expansion of arrays in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:docexcel.net. If there is any infringement, please contact admin@php.cn delete