[英]Print an array like an object in Java
我知道数组是Java中的一个对象。 我想像其他对象一样打印一个数组,但这不起作用:
public static Object[] join(Object[] obj1,Object[] obj2)
{
Object[] sum=new Object[obj1.length+obj2.length];
int i=0;
for(;i<obj1.length;i++)
{
sum[i]=obj1[i];
}
for(int j=0;j<obj2.length;j++,i++) {
sum[i]=obj2[j];
// i++;
}
return sum;
}
public static void main(String[] args) {
// TODO code application logic here
int[] array={1,2,3,4,5};
Object[] obj1={"Nguyen Viet Q",28,"Doan Thi Ha",array};
Object[] obj2={"Nguyen Viet Q1",28,"Doan Thi Ha1"};
join(obj1,obj2);
for(Object o: join(obj1,obj2))
{
System.out.print(o.toString()+" ");// i want to print array object
}
}
有人可以帮帮我吗?
首先你的join
方法只需要一个循环来复制obj2
和obj1
。 您可以找到循环测试的最大长度。 然后复制每个有效索引。 这可能看起来像
public static Object[] join(Object[] obj1, Object[] obj2) {
Object[] sum = new Object[obj1.length + obj2.length];
int len = Math.max(obj1.length, obj2.length);
for (int i = 0; i < len; i++) {
if (i < obj1.length) {
sum[i] = obj1[i];
}
if (i < obj2.length) {
sum[i + obj1.length] = obj2[i];
}
}
return sum;
}
然后你需要保存对你加入的obj
的引用(或直接print
)。 并且因为它包含嵌套数组,您可以选择Arrays.deepToString(Object[])
public static void main(String[] args) {
int[] array = { 1, 2, 3, 4, 5 };
Object[] obj1 = { "Nguyen Viet Quan", 28, "Doan Thi Ha", array };
Object[] obj2 = { "Nguyen Viet Quan1", 28, "Doan Thi Ha1" };
System.out.println(Arrays.deepToString(join(obj1, obj2)));
}
哪个输出(为此帖格式化)
[Nguyen Viet Quan, 28, Doan Thi Ha, [1, 2, 3, 4, 5],
Nguyen Viet Quan1, 28, Doan Thi Ha1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.