Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit dc34cae

Browse files
Challenge 5.
Java 9 Collection Factories. Unmodifiable collection. Set.of() exception
1 parent 8c44c30 commit dc34cae

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

‎src/main/java/Challenge_5.java‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import java.util.ArrayList;
2+
import java.util.Collection;
3+
import java.util.List;
4+
import java.util.Set;
5+
import java.util.stream.Collectors;
6+
7+
/**
8+
* In this challenge we have:
9+
* + when creating collection using the of method, we create immutable collection, so
10+
* for example: List<String> list = List.of(); we can't modify the list.
11+
* as a result an exception is thrown.
12+
*
13+
* + Set.of() and Set.copyOf() return an unmodifiable Set.
14+
* Set.of("Joker","Riddler","Joker") will throw an exception as the arguments contains duplicate elements.
15+
*/
16+
public class Challenge_5{
17+
18+
public static void main( String[] args ) {
19+
final Collection<Object> finalDcCharacters = new ArrayList<>();
20+
List<String> list = List.of(); //empty list
21+
Set<Object> set = Set.of(); //empty set
22+
23+
try {
24+
list.add("Deadpool"); // all mutating methods throw UnsupportedOperationException
25+
}catch (UnsupportedOperationException e){
26+
System.out.println("no space fro Marvel hero here");
27+
}
28+
29+
try {
30+
final List<Object> objects = set.stream().collect(Collectors.toList());
31+
boolean added = objects.add("Harley Quinn");
32+
System.out.println("added "+added);
33+
finalDcCharacters.addAll(new ArrayList<>(set));
34+
}catch (UnsupportedOperationException | IllegalArgumentException e){
35+
System.out.print("no space for villains");
36+
System.exit(0);
37+
}
38+
try {
39+
var villains = Set.copyOf(set);//this method return an unmodifiable Set
40+
finalDcCharacters.addAll(List.of(villains, Set.of("Joker","Riddler","Joker")));
41+
}catch (IllegalArgumentException e){
42+
System.out.println("Where are the villains?");
43+
}
44+
finalDcCharacters.forEach(System.out::println);
45+
}
46+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /