如何在Java中向数组添加元素?
数组是一种线性数据结构,用于存储一组具有相似数据类型的元素。它以顺序方式存储数据。一旦我们创建了一个数组,我们就无法更改其大小,即它是固定长度的。向给定数组添加元素是一个非常常见的操作。在本文中,我们将通过 Java 示例程序讨论如何向数组添加元素。
在Java中向数组添加元素
让我们先用一个例子来理解这个操作:
我们将在上述数组的末尾添加一个新元素“50”。新的数组将变成
数组语法
Data_Type nameOfarray[] = {values separated with comma};
方法1
创建一个整数类型的数组,并将它的长度存储到一个整型变量中。
现在,创建一个另一个整数类型的数组,但大小比之前的数组大一个。
接下来,使用for循环将第一个数组的元素复制到第二个数组中,并在复制后添加一个新元素。
最后,使用另一个for循环打印新数组。
示例
在下面的示例中,我们将使用for循环向给定数组添加元素。
import java.util.*;
public class Increment {
public static void main(String[] args) {
int aray[] = {25, 30, 35, 40, 45};
int sz = aray.length;
System.out.print("The given array: ");
// to print the older array
for(int i = 0; i < sz; i++) {
System.out.print(aray[i] + " ");
}
System.out.println();
int newAray[] = new int[sz + 1];
int elem = 50;
// to append the element
for(int i = 0; i < sz; i++) {
newAray[i] = aray[i]; // copying element
}
newAray[sz] = elem;
System.out.print("The new array after appending the element: ");
// to print new array
for(int i = 0; i < newAray.length; i++) {
System.out.print(newAray[i] + " ");
}
}
}
输出
The given array: 25 30 35 40 45 The new array after appending the element: 25 30 35 40 45 50
方法2
创建一个Integer类型的数组。“Integer”是一个包装类。使用for循环显示数组。
现在,使用`Arrays.asList()`方法用之前的数组定义一个ArrayList。此方法将数组作为参数,并将其返回为List。
接下来,使用内置方法`add()`向ArrayList添加一个新元素。
显示结果并退出。
示例
在下面的示例中,我们将使用ArrayList向给定数组添加元素。
import java.util.*;
public class Increment {
public static void main(String[] args) {
Integer aray[] = {25, 30, 35, 40, 45};
int sz = aray.length;
System.out.print("The given array: ");
for(int i = 0; i < sz; i++) {
System.out.print(aray[i] + " ");
}
System.out.println();
// creating an ArrayList with old array
ArrayList<Integer> arayList = new
ArrayList<Integer>(Arrays.asList(aray));
arayList.add(50); // adding new element
System.out.print("The new array after appending the element: " + arayList);
}
}
输出
The given array: 25 30 35 40 45 The new array after appending the element: [25, 30, 35, 40, 45, 50]
结论
与其他编程语言不同,Java没有提供任何内置方法来向数组追加元素。原因是数组是固定大小的。因此,我们需要编写自定义逻辑来向数组添加元素。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP