简体   繁体   English

覆盖二维数组列表中的一行

[英]Overwriting a row in a two dimensional arraylist

I have a 2D arraylist containing 4 cols. 我有一个包含4个列的2D arraylist。 I want to add a 5 th column to this arraylist. 我想在此arraylist中添加第5列。 the fourth col is a set of values based on which the result is to be added as the 5th column. 第四列是一组值,基于该值,结果将被添加为第五列。 If 1st row has 4th element as 0 then the fifth column will have a result string "Failure" 如果第一行的第4元素为0,则第五列的结果字符串为“ Failure”

Is it ok to use a 1D arraylist to get all the elements of the 2D arraylist and add the 5th element to it and then overwrite the 2D with the 1D arraylist items OR Is there a way we can directly append to the 2D arraylist using the index() and indexOF()? 是否可以使用1D数组列表获取2D数组列表的所有元素并向其添加第5个元素,然后用1D数组列表项覆盖2D,还是可以使用索引直接将其附加到2D数组列表? ()和indexOF()?

Will appreciate it if someone can help me out with this. 如果有人可以帮助我,将不胜感激。

Java doesn't support first-class multi-dimensional arrays. Java不支持一流的多维数组。 A two dimensional array is an 'array of arrays'. 二维数组是“数组数组”。 Java also does not support resizing of arrays. Java还不支持调整数组的大小。

Assuming you've already got data in your String[][] table: 假设您的String [] []表中已经有数据:

String[][] table = /* init from somewhere */;

for (int i = 0; i < table.length; i++) {
   String[] row = table[i];
   assert (row.length == 4);
   String[] newRow = Arrays.copyOf(row, 5);
   assert (newRow.length == 5);
   newRow[4] = "Failure";
   table[i] = newRow;
}

That's approximately how you'd handle adding a column. 大概就是您要添加列的方式。 Notice that Arrays.copyOf() is much better than copying the array's contents 'by hand'. 注意,Arrays.copyOf()比“手动”复制数组的内容要好得多。

(note: when you run this sample, use the -ea flag to the JVM so that the assertions fire) (注意:运行此示例时,请对JVM使用-ea标志,以便触发断言)

You should be able to use ArrayList#add 您应该可以使用ArrayList#add

for(ArrayList<Object> a: in aa){
    a.add(a.get(3) == 0 ? "failure" : "success")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM