You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 55c61b5
Browse filesBrowse the repository at this point in the historyBrowse files
Copy file name to clipboardExpand all lines: exercises/binary-search/README.md
+27Lines changed: 27 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -34,6 +34,33 @@ A binary search halves the number of items to check with each iteration,
34
34
so locating an item (or determining its absence) takes logarithmic time.
35
35
A binary search is a dichotomic divide and conquer search algorithm.
36
36
37
+
This exercise introduces [generics](https://docs.oracle.com/javase/tutorial/java/generics/index.html).
38
+
To make the tests pass you need to construct your class such that it accepts any type of input, e.g. `Integer` or `String`.
39
+
40
+
Generics are useful because they allow you to write more general and reusable code.
41
+
The Java [List](https://docs.oracle.com/javase/8/docs/api/java/util/List.html) and [Map](https://docs.oracle.com/javase/8/docs/api/java/util/Map.html) implementations are both examples of classes that use generics.
42
+
By using them you can construct a `List` containing `Integers` or a list containing `Strings` or any other type.
43
+
44
+
There are a few constraints on the types used in generics.
45
+
One of them is that once you've constructed a `List` containing `Integers`, you can't put `Strings` into it.
46
+
You have to specify which type you want to put into the class when you construct it, and that instance can then only be used with that type.
47
+
48
+
For example you could construct a list of `Integers`:
49
+
50
+
`List<Integer> someList = new LinkedList<>();`
51
+
52
+
Now `someList` can only contain `Integers`. You could also do:
53
+
54
+
`List<String> someOtherList = new LinkedList<>()`
55
+
56
+
Now `someOtherList` can only contain `Strings`.
57
+
58
+
Another constraint is that any type used with generics cannot be a [primitive type](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html), such as `int` or `long`.
59
+
However, every primitive type has a corresponding reference type, so instead of `int` you can use [`Integer`](https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html) and instead of `long` you can use [`Long`](https://docs.oracle.com/javase/8/docs/api/java/lang/Long.html).
60
+
61
+
It can help to look at an [example use case of generics](https://docs.oracle.com/javase/tutorial/java/generics/types.html) to get you started.
0 commit comments