BAEL-4236 | Add code examples to handle IndexOutOfBoundsException and alternatives to make a copy of the l.ist

This commit is contained in:
Vishal
2020-10-27 13:10:58 +05:30
parent 8731cda3b9
commit 943fa43822
10 changed files with 172 additions and 0 deletions
@@ -0,0 +1,14 @@
package com.baeldung.indexoutofbounds;
import java.util.ArrayList;
import java.util.List;
public class CopyListUsingAddAllMethodDemo {
static List<Integer> copyList(List<Integer> source) {
List<Integer> destination = new ArrayList<>();
destination.addAll(source);
return destination;
}
}
@@ -0,0 +1,10 @@
package com.baeldung.indexoutofbounds;
import java.util.Collections;
import java.util.List;
public class CopyListUsingCollectionsCopyMethodDemo {
static void copyList(List<Integer> source, List<Integer> destination) {
Collections.copy(destination, source);
}
}
@@ -0,0 +1,10 @@
package com.baeldung.indexoutofbounds;
import java.util.ArrayList;
import java.util.List;
public class CopyListUsingConstructorDemo {
static List<Integer> copyList(List<Integer> source) {
return new ArrayList<>(source);
}
}
@@ -0,0 +1,12 @@
package com.baeldung.indexoutofbounds;
import java.util.List;
import java.util.stream.Collectors;
public class CopyListUsingJava8StreamDemo {
static List<Integer> copyList(List<Integer> source) {
return source
.stream()
.collect(Collectors.toList());
}
}
@@ -0,0 +1,13 @@
package com.baeldung.indexoutofbounds;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class IndexOutOfBoundsExceptionDemo {
static List<Integer> copyList(List<Integer> source) {
List<Integer> destination = new ArrayList<>(source.size());
Collections.copy(destination, source);
return destination;
}
}