Skip to content

Commit 8010ef8

Browse files
committed
Update challenges.md
1 parent 7dc4583 commit 8010ef8

1 file changed

Lines changed: 80 additions & 0 deletions

File tree

src/generics/challenges.md

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,85 @@ Remember the rules for this are
55
- Try to use only the information given up to this point in this book.
66
- Try not to give up until you've given it a solid attempt
77

8+
9+
810
## Challenge 1.
911

12+
13+
Will the following code work? Why or why not?
14+
15+
```java
16+
class Thing<T> {
17+
T value;
18+
}
19+
20+
class Cool {
21+
}
22+
class NotCool {
23+
}
24+
25+
class Main {
26+
void main() {
27+
int n = Integer.parseInt(
28+
IO.readln("Give a number: ")
29+
);
30+
31+
Thing<Object> o = (n % 2 == 0)
32+
? new Thing<Cool>()
33+
: new Thing<NotCool>();
34+
35+
}
36+
}
37+
```
38+
39+
## Challenge 2.
40+
41+
Make a class that holds a `NotNull` value. This class should be generic over the kind of
42+
data that it holds but it should throw an exception if the provided `value` is `null`.
43+
44+
```java,editable
45+
// CODE HERE
46+
47+
class Main {
48+
void main() {
49+
NotNull<String> s = new NotNull<>("abc");
50+
IO.println(s.value);
51+
52+
NotNull<Integer> i = new NotNull<>(123);
53+
IO.println(i.value);
54+
55+
// This should throw an exception
56+
// NotNull<Double> d = new NotNull<>(null);
57+
}
58+
}
59+
```
60+
61+
62+
## Challenge 3.
63+
64+
The following class has 5 generic parameters.
65+
66+
Correct the ones which do not follow expected naming conventions
67+
68+
69+
```java,editable
70+
class Organism<name, h, T, Cat, inch_worm> {
71+
name name;
72+
h h;
73+
T t;
74+
Cat cat;
75+
inch_worm inchWorm;
76+
}
77+
78+
class Main {
79+
void main() {
80+
var o = new Organism<String, Integer, Integer, String, String>();
81+
o.name = "abc";
82+
o.h = 123;
83+
o.t = 5;
84+
o.cat = "...";
85+
o.inchWorm = "\\_/-\\--(*)";
86+
}
87+
}
88+
```
89+

0 commit comments

Comments
 (0)