BAEL-4236 | Add code examples to handle IndexOutOfBoundsException and alternatives to make a copy of the l.ist
This commit is contained in:
+14
@@ -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;
|
||||
}
|
||||
}
|
||||
+10
@@ -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);
|
||||
}
|
||||
}
|
||||
+10
@@ -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);
|
||||
}
|
||||
}
|
||||
+12
@@ -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());
|
||||
}
|
||||
}
|
||||
+13
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user