我正在使用Netbeans,而且我编写的方法并没有完全符合它的要求:
private ArrayList<String[]>ProductsInStock;
public void DisplayStock() {
ArrayList<String[]> Sort = new ArrayList<String[]>();
System.out.println("");
for (int i = 0; i < ProductsInStock.size(); i++) {
if (ProductsInStock.get(i)[2].equals(Products.get(ProductCodeCB.getSelectedIndex())[1])) {
boolean foundColor = false;
int size = Sort.size();//Since the size will differ dynamically
for (int k = 0; k < size; k++) {
if (Sort.get(k)[3].equals(ProductsInStock.get(i)[3])) {
foundColor = true;
if (Sort.get(k)[4].equals(ProductsInStock.get(i)[4])) {
String S[] = Sort.get(k);
S[5] = (Integer.parseInt(Sort.get(k)[5]) + Integer.parseInt(ProductsInStock.get(i)[5])) + "";
Sort.set(k, S);
break;
}
if (k == Sort.size() - 1) {
Sort.add(ProductsInStock.get(i));
}
} else if (foundColor == true) {
Sort.add(k, ProductsInStock.get(i));
break;
}
}
System.out.print(ProductsInStock.get(0)[5]+" ");
if (foundColor == false) {
Sort.add(ProductsInStock.get(i));
}
}
}
}
}
该方法不应该更改ProductsInStock.get(0)[5]的值,但每次调用该方法时它都会递增1,我已经放置了“System.out.println()”来显示你是如何实际改变价值的。结果如下:1 1 1 1 1 1 1 1 2 当我添加“S [5] = ProductsInStock.get(i)[5];”这一行时,结果变为:1 1 1 1 1 1 1 1 1(应该如此):
public void DisplayStock() {
ArrayList<String[]> Sort = new ArrayList<String[]>();
System.out.println("");
for (int i = 0; i < ProductsInStock.size(); i++) {
if (ProductsInStock.get(i)[2].equals(Products.get(ProductCodeCB.getSelectedIndex())[1])) {
boolean foundColor = false;
int size = Sort.size();//Since the size will differ dynamically
for (int k = 0; k < size; k++) {
if (Sort.get(k)[3].equals(ProductsInStock.get(i)[3])) {
foundColor = true;
if (Sort.get(k)[4].equals(ProductsInStock.get(i)[4])) {
String S[] = Sort.get(k);
S[5] = (Integer.parseInt(Sort.get(k)[5]) + Integer.parseInt(ProductsInStock.get(i)[5])) + "";
Sort.set(k, S);
S[5]=ProductsInStock.get(i)[5]; //<<<<HERE>>>>
break;
}
if (k == Sort.size() - 1) {
Sort.add(ProductsInStock.get(i));
}
} else if (foundColor == true) {
Sort.add(k, ProductsInStock.get(i));
break;
}
}
System.out.print(ProductsInStock.get(0)[5]+" ");
if (foundColor == false) {
Sort.add(ProductsInStock.get(i));
}
}
}
}
如您所见,没有一个“ProductsInStock.set()”或“ProductsInStock.get()[] =”来更改arraylist中的任何值。
答案 0 :(得分:3)
当你这样写:
Sort.add(ProductsInStock.get(i));
您要将ProductsInStock.get(i)
数组的引用添加到Sort
列表中。 Sort.get(Sort.size()-1)
中所做的任何更改都会影响原始数组。
因此代码如
String S[] = Sort.get(k);
S[5] = ...
修改ProductsInStock
List。
为了避免这种情况,您应该在将数组添加到其他列表之前创建数组的副本:
Sort.add(Arrays.copyOf(ProductsInStock.get(i),ProductsInStock.get(i).length));