[英]How can I remove value from a list based off it's location from a copy of that list?
我正在嘗試根據值列表中的位置刪除這些特定項目。 下面的代碼由於復制列表縮小太多而引發錯誤
private ArrayList<String> removeGen(int addLines, int labLines, int venLines, ArrayList<String> values){
ArrayList<String> copy = new ArrayList<>();
copy = (ArrayList<String>) values.clone();
for(int i = 0; i < values.size(); i++) {
if (i > 100 && i < (100 + (addLines * 5) + 1)) {
copy.remove(i);
}
if (i > (100 + (addLines * 5)) + 9 && i < 100 + (addLines * 5) + (labLines * 4) + 10) {
copy.remove(i);
}
if (i > 100 + (addLines * 5) + (labLines * 4) + 21 && i < 100 + (addLines * 5) + (labLines * 4) + (venLines * 4) + 22) {
copy.remove(i);
}
}
return copy;
問題是某些值彼此之間無法區分,因此我也不能使用remover(obj)。
如何返回在上述位置刪除了值的列表?
您要刪除的是索引而不是按值刪除,但是您忘記了刪除某些內容后, values
的索引不是copy
中的索引。 刪除后,每個對象都會獲得另一個索引,因此列表不再相同。
示例:刪除索引4之后,索引5將在索引4上獲得新值。此切換效果將一直持續到列表末尾。
因此,有兩種方法可以使這一方法正確:
copy
並將此列表返回。 return copy.filter(x -> x != null).collect(Collectors.toList());
如果您使用的是Java 7及更低版本,則可以使用copy.removeAll(Collections.singleton(null));
這是第一個結果:
ArrayList<String> copy = new ArrayList<>();
for(int i = 0; i < values.size(); i++) {
if (i < 100 && i > (100 + (addLines * 5) + 1)) {
copy.add(values.get(i));
}
if (i < (100 + (addLines * 5)) + 9 && i > 100 + (addLines * 5) + (labLines * 4) + 10) {
copy.add(values.get(i));
}
if (i < 100 + (addLines * 5) + (labLines * 4) + 21 && i > 100 + (addLines * 5) + (labLines * 4) + (venLines * 4) + 22) {
copy.add(values.get(i));
}
}
return copy;
這是第二個結果:
ArrayList<String> copy = new ArrayList<>();
copy = (ArrayList<String>) values.clone();
for(int i = 0; i < values.size(); i++) {
if (i > 100 && i < (100 + (addLines * 5) + 1)) {
copy.get(i) = null;
}
if (i > (100 + (addLines * 5)) + 9 && i < 100 + (addLines * 5) + (labLines * 4) + 10) {
copy.get(i) = null;
}
if (i > 100 + (addLines * 5) + (labLines * 4) + 21 && i < 100 + (addLines * 5) + (labLines * 4) + (venLines * 4) + 22) {
copy.get(i) = null;
}
}
return copy.filter(x -> x != null).collect(Collectors.toList());
private ArrayList<Integer> removeGen(int addLines, int labLines, int venLines, ArrayList<String> values){
ArrayList<String> copy = new ArrayList<>();
ArrayList<Integer> numbers = new ArrayList<>();
copy = (ArrayList<String>) values.clone();
for(int i = 0; i < values.size(); i++) {
if (i > 100 && i < (100 + (addLines * 5) + 1)) {
//copy.remove(i);
}
else if(i > (100 + (addLines * 5)) + 9 && i < 100 + (addLines * 5) + (labLines * 4) + 10) {
//copy.remove(i);
}
else if(i > 100 + (addLines * 5) + (labLines * 4) + 21 && i < 100 + (addLines * 5) + (labLines * 4) + (venLines * 4) + 22) {
//copy.remove(i);
}
else {
numbers.add(i);
}
}
return numbers;
}
只是做了相反的事情並提取了我需要的位置,應該對其他人有幫助
ArrayList<Integer> tempList = removeGen(additional,labour,vendor,values);
for (int j = 0; j < tempList.size(); j++) {
template = template.replaceFirst(section + j, values.get(tempList.get(j)));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.