If first.size() is more than second.size() then the resultant list should be of the size of first else it should be the size of second.
import java.util.ArrayList;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;
public class Source {
public static List<Integer> getSumOfListElements(List<Integer> first,List<Integer> second){
if(first.size()>=second.size()){
List<Integer> third = new ArrayList<Integer>();
for (int i = 0; i < first.size(); i++) {
third.add(first.get(i) + second.get(i));
}
return third;
}else{
List<Integer> third = new ArrayList<Integer>();
for (int i = 0; i < second.size(); i++) {
third.add(first.get(i) + second.get(i));
}
return third;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
String str2 = in.nextLine();
System.out.println(str);
System.out.println(str2);
List<Integer> list1 = Arrays.stream(str.split("\\s"))
.mapToInt(Integer::parseInt)
.boxed()
.collect(Collectors.toList());
List<Integer> list2 = Arrays.stream(str2.split("\\s"))
.mapToInt(Integer::parseInt)
.boxed()
.collect(Collectors.toList());
System.out.println(list1.size());
System.out.println(list2.size());
List<Integer> actual = Source.getSumOfListElements(list1,list2);
System.out.println(actual);
}
}
This is the code that I have written. It is giving exception Operation not permitted.
Your code does not work because when you try to add two numbers from lists (say first list size=20, and second list size=10), at one point i
become larger than second list. When your for loop try to find element for that i
, you will get an error.
To eradicate this, you should use a try catch block to bypass addition and add remaining elements of large list directly.
Take a look at the following code:
public static List<Integer> getSumOfListElements(List<Integer> first, List<Integer> second) {
// declare 'third' list with size of max('first' list, 'second' list)
List<Integer> third = new ArrayList<>(Math.max(first.size(), second.size()));
// loop through max('first' list, 'second' list) number elements in both lists
for (int i = 0; i < Math.max(first.size(), second.size()); i++) {
try {
third.add(first.get(i) + second.get(i));
// at one point either first or second will be finished.
// (say second is finished at this point)
// then add remaining elements of first to third
} catch (IndexOutOfBoundsException e) {
if (first.size() > second.size()) third.add(first.get(i));
else third.add(second.get(i));
}
}
return third;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.