Java –将值附加到Object []数组中

在此示例中,我们将向您展示如何在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

intInteger转换有点奇怪……如果您有更好的主意,请告诉我。

参考文献

  1. Apache ArrayUtils JavaDoc
  2. Java –将int []转换为Integer []示例

翻译自: https://mkyong.com/java/java-append-values-into-an-object-array/

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值