2017-10-17 47 views
-3

我想減去兩個數組列表。 兩者的ArrayList包含以下數據減2列表列表

[1, 1, 5, 1, 1] 

我使用Apache庫執行操作。

List resultList = ListUtils.subtract(sections, sections); 

操作完成,但我的結果如下

[] 

當我需要它是

[0, 0, 0, 0, 0] 

我怎麼會去這樣做呢?

+1

你應該看'ListUtils.subtract'的文件開始暗示:它不會做你的想法。 http://idownvotedbecau.se/noresearch/ – Oleg

+0

'section.replaceAll(e - > 0);' – shmosel

+1

[如何減去Java中兩個列表/數組的值](https://stackoverflow.com/問題/ 40644999 /如何對減去值 - 的 - 兩列表陣列式的Java) – azurefrog

回答

0

爲什麼不直接用for循環做呢?

// Initialize both lists 
List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(1, 1, 5, 1, 1)); 
List<Integer> list2 = new ArrayList<Integer>(Arrays.asList(1, 1, 5, 1, 1)); 

for(int i=0; i < list1.size(); ++i){ 
    // This is doing the subtraction and assigning the values to 
    // list1. If you need a new list, declare it and proceed similarly 
    list1.set(i, list1.get(i) - list2.get(i)); 
} 
System.out.println(list1); // output: [0, 0, 0, 0, 0] 

你可以看一下一些信息在set功能在這裏:https://www.tutorialspoint.com/java/util/arraylist_set.htm