Java - Object[]配列に値を追加する

Java –値をObject []配列に追加します

この例では、Object[]およびint[]配列に値を追加する方法を示します。

    Object[] obj = new Object[] { "a", "b", "c" };
    ArrayList newObj = new ArrayList(Arrays.asList(obj));
    newObj.add("new value");
    newObj.add("new value 2");


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) {

    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[]に値を追加するには、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 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からIntegerへの変換は少し奇妙です…もっと良いアイデアがあれば教えてください。

参考文献

Related