【发布时间】:2020-06-25 09:03:26
【问题描述】:
我有一个列表,里面有 2 个列表,就像一个矩阵,在我填充这个列表之后,我使用循环执行一些计算,以填充第三个列表,但这不能正常工作。 我有一个 if 语句来检查值是否相同,但它只工作一次,在找到匹配项后它不会再次找到另一个匹配项,对不起我的代码我是初学者
代码如下:
List<List<String>> dynamic2D = new ArrayList<List<String>>();
dynamic2D.add(new ArrayList<String>());
dynamic2D.add(new ArrayList<String>());
dynamic2D.get(0).add("type2"); //populate first inner list
dynamic2D.get(0).add("type3");
dynamic2D.get(0).add("type1");
dynamic2D.get(0).add("type2");
dynamic2D.get(1).add("1"); //populate second inner list
dynamic2D.get(1).add("3");
dynamic2D.get(1).add("5");
dynamic2D.get(1).add("6");
ArrayList<String> amountOfTypes = new ArrayList<>(); //After deleting repeated values I get the amount of types existing on my first inner list
amountOfTypes.add("type1");
amountOfTypes.add("type2");
amountOfTypes.add("type3");
ArrayList<Integer> amountOfValuesOfTypes =new ArrayList<>();
// I populate this list with 0 values to later make a Sum of each value existing in the second inner list that correspond to the first inner list
for(int i = 0; i<amountOfTypes.size();i++){ // Here I have a list with 3 zero values, {0,0,0}, because there are 3 types of values
amountOfValuesOfTypes.add(0);
}
// Now here is the problem, Im trying to sum the respective values of each type, that correspond with the second inner list. in order to get the raw amount.
for(int i = 0; i<amountOfTypes.size();i++){
for(int j = 0; i<dynamic2D.get(0).size();j++){ // a second inner loop to compare the value of my main list(that has all the values) with the filtered list (that only have values that do not repeat)
if(amountOfTypes.get(i) == dynamic2D.get(0).get(j)){
int secondListIntToString= Integer.valueOf(dynamic2D.get(1).get(j)); // Here I get the corresponding match Integer Value
amountOfTypes.set(i,amountOfValuesOfTypes.get(i)+secondListIntToString); // Here I take the values that match by THE CRITERIA OF HAVING THE SAME VALUE IN THE FIRST INNER LIST, and make a sum to have the full value, but when there is a match it only sum ONCE, and it doesnt happen again
}
}
}
感谢您的帮助。
【问题讨论】:
标签: java if-statement arraylist nested-loops