Home > Java > javaTutorial > body text

How to expand array in java

王林
Release: 2023-05-20 15:25:06
forward
2610 people have browsed it

1. Principle of expansion

(1) The size of Java array objects is fixed, and array objects cannot be expanded.

(2) Array expansion can be achieved flexibly by using the array copy method.

(3) System.arraycopy() can copy an array.

(4) Arrays.copyOf() can easily create a copy of an array.

(5) When creating a copy of the array and increasing the length of the array, the expansion of the array can be realized in a flexible way.

2. Create the array first

import java.util.Arrays;
//数组的扩容示例
public class Test {
public static void main(String [] args){
//创建一个原始数组,并做好初始化。
// int [] arry = {1,3,5,7,9};
int arry[] =new int[]{1,3,5,7,9};
int arry1[]=new int[7];//新建一个新数组这里的7=arry.length+需要扩容的长度
System.out.println("打印原始数组的长度为:"+arry.length);
System.out.println("打印新数组的长度为:"+arry1.length);
//验证该数组有没有创建完成,可以获取一下数组元素看看能不能成功。
// System.out.println(arry[1]);
//把从旧数组中获取的数据一个一个的存到新的数组里面去,并新增两个数:11,13。
//如何把数据存到数组里面去,使用arry1[0]=1;
/*
Copy after login

3. Method 1: Loop through the original array arry, the length is fixed, so use a for loop.

//1、先完成复制数组
for(int i=0;i<arry.length;i++){
arry1[i] = arry[i];
}
//2、再完成赋值插入操作,即已完成数组的扩容操作。
arry1[5]=11;
arry1[6]=13;
System.out.println("新数组为:"+arry1[5]);
System.out.println("新数组为:"+arry1[6]);
*/
/*
Copy after login

4. Method 2: Use the copyOf (original array name, new array length) method of the Arrays class of the java util package to copy.

arry1 = Arrays.copyOf(arry,arry.length+2);
arry1[5] = 11;
arry1[6] = 13;
System.out.println("新数组为:"+arry1[5]);
System.out.println("新数组为:"+arry1[6]);
*/
Copy after login

The above is the detailed content of How to expand array in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template