如何在 java 中像这样"List<Object[]> listObject"将元素添加到该变量列表中?



如果squareBrack中的类型数据是array,我不知道如何添加元素。

如果您想在List中添加元素,那么只需执行:

listObject.add(new Object[]{});

或者,如果您想添加到列表中的Object数组,则使用(由于数组数据结构的限制行为,这是一个相当长的根,这就是为什么ArrayList是实现这一点的替代方案。(:

@Test
public void testArray()  {

List<Object[]> listObjects =  new ArrayList<>();
listObjects.add(new Object[]{1,2});
addX( listObjects.get(0).length , listObjects.get(0) , 3);
listObjects.set(0,addX( listObjects.get(0).length , listObjects.get(0) , 3));
System.out.println(listObjects.get(0));
}
public Object[] addX(int n, Object arr[], Object x)
{
int i;
// create a new array of size n+1
Object newarr[] = new Object[n + 1];
// insert the elements from
// the old array into the new array
// insert all elements till n
// then insert x at n+1
for (i = 0; i < n; i++)
newarr[i] = arr[i];
newarr[n] = x;
return newarr;

}

最新更新