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 temp = new ArrayList(Arrays.asList(obj));
temp.add(newObj);
return temp.toArray();
}
}
Выход
Before Object []
a
b
c
After Object []
a
b
c
new value
2. инт [] Пример массива
Чтобы добавить значения в массив примитивного типа – int[] , вам нужно знать, как конвертировать int[] и Целое число[] . В этом примере мы используем класс ArrayUtils из общей сторонней библиотеки Apache для обработки преобразования.
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 newObj =
new ArrayList(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 в Целое число немного странно… Пожалуйста, дайте мне знать, если у вас есть идея получше.