Example. The GuestList interface (Object version)

[comp1110-49]

The original GuestList interface used String throughout. Replacing String with Object allows any type of value to be stored, since every Java class is a subtype of Object:

public interface GuestList { // record that a guest is coming void add(Object name); // record that a guest is no longer coming void remove(Object name); // query whether a guest is coming boolean isComing(Object name); }

Our implementations (both strict and lazy) can be easily adapted by replacing the type String with Object throughout. Because Object already specifies the equals method, we've gained a lot of flexibility for essentially no cost, which is great! The tricky part comes when we are also supposed to return values stored in our list.

Consider our previous extension of the above interface where we also return a list of everyone who is coming, this time with Object:

Object[] coming();

This method now returns an array of Objects, when our testing code would presumably expect an array of Strings. We can adjust our testing code to expect Object arrays, and we can explicitly cast the elements of the array to our expected type.

However, this approach sacrifices type safety. Nothing prevents a caller from adding a mix of unrelated types to the same list, and retrieving a value requires an explicit cast (e.g. (String) list.coming()[0]) that can fail at runtime with a ClassCastException. The compiler cannot catch such errors.

bars magnifying-glass caret-down plus minus arrow-right xmark