Skip to Content
Java Projects - Second Edition
book

Java Projects - Second Edition

by Peter Verhas
August 2018
Intermediate to advanced
524 pages
14h 45m
English
Packt Publishing
Content preview from Java Projects - Second Edition

Collections with wrong elements

A bug is not trivial, and as usual, this is not in the implementation of the algorithm, but rather in the definition, or the lack of it. What should the program do if there are not only strings in the collection that we sort?

If I create a new test that starts with the following lines, it will throw ClassCastException:

@Test(expected = ClassCastException.class)
public void canNotSortMixedElements() {
    var actualNames = new ArrayList(Arrays.asList(
        42, "Wilson",
        "Wilkinson", "Abraham", "Dagobert"
    ));
    //... the rest of the code is the same as the previous test

The problem here is that Java collections can contain any type of element. You cannot ever be sure that a collection, such as ArrayList, contains only the ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Java 11 Cookbook - Second Edition

Java 11 Cookbook - Second Edition

Nick Samoylov, Mohamed Sanaulla

Publisher Resources

ISBN: 9781789131895Supplemental Content