Java –値をObject []配列に追加します
この例では、Object[]
およびint[]
配列に値を追加する方法を示します。
Object[] obj = new Object[] { "a", "b", "c" }; ArrayList
1. Object []配列の例
ArrayList
で値を追加する例:
TestApp.java
package com.example.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) { ArrayListtemp = 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[]
に値を追加するには、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[] ArrayListnewObj = 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
からInteger
への変換は少し奇妙です…もっと良いアイデアがあれば教えてください。
参考文献
-
Java – Convert int[からInteger []の例]