在此示例中,我们将向您展示如何在Object[]
和int[]
数组中附加值。
Object[] obj = new Object[] { "a", "b", "c" };
ArrayList<Object> newObj = new ArrayList<Object>(Arrays.asList(obj));
newObj.add("new value");
newObj.add("new value 2");
1. Object []数组示例
使用ArrayList
示例:
TestApp.java
package com.mkyong.test;
import java.util.ArrayList;
import java.util.Arrays;
public class TestApp {
public static void main(String[] args) {
TestApp test = new TestApp();
test.process();
}
private void process() {
Object[] obj = new Object[] { "a", "b", "c" };
System.out.println("Before Object [] ");
for (Object temp : obj) {
System.out.println(temp);
}
System.out.println("\nAfter Object [] ");
Object[] newObj = appendValue(obj, "new Value");
for (Object temp : newObj) {
System.out.println(temp);
}
}
private Object[] appendValue(Object[] obj, Object newObj) {
ArrayList<Object> temp = new ArrayList<Object>(Arrays.asList(obj));
temp.add(newObj);
return temp.toArray();
}
}
输出量
Before Object []
a
b
c
After Object []
a
b
c
new value
2. int []数组示例
要在原始类型数组– int[]
,您需要知道如何在int[]
和Integer[]
之间进行转换。 在此示例中,我们使用来自Apache通用第三方库的ArrayUtils
类来处理转换。
TestApp2.java
package com.hostingcompass.test;
import java.util.ArrayList;
import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils;
public class TestApp2 {
public static void main(String[] args) {
TestApp2 test = new TestApp2();
test.process();
}
private void process() {
int[] obj = new int[] { 1, 2, 3 };
System.out.println("Before int [] ");
for (int temp : obj) {
System.out.println(temp);
}
System.out.println("\nAfter Object [] ");
int[] newObj = appendValue(obj, 99);
for (int temp : newObj) {
System.out.println(temp);
}
}
private int[] appendValue(int[] obj, int newValue) {
//convert int[] to Integer[]
ArrayList<Integer> newObj =
new ArrayList<Integer>(Arrays.asList(ArrayUtils.toObject(obj)));
newObj.add(newValue);
//convert Integer[] to int[]
return ArrayUtils.toPrimitive(newObj.toArray(new Integer[]{}));
}
}
输出量
Before int []
1
2
3
After Object []
1
2
3
99
从int
到Integer
转换有点奇怪……如果您有更好的主意,请告诉我。
参考文献
翻译自: https://mkyong.com/java/java-append-values-into-an-object-array/