newToProgramming
newToProgramming

Reputation: 8275

Generics List Interface

The List interface is the following:

public interface List<E>{
public boolean add(Object e);
public boolean remove(Object e);
public boolean contains(Object e);
...etc

Why aren't the add, remove and contains methods written like the following?

public boolean add(E e)
public boolean remove(E e)
public boolean contains(E e)

Upvotes: 4

Views: 221

Answers (4)

leedm777
leedm777

Reputation: 24032

The add method is add(E e), so all is right with the world in that respect.

The remove(Object o) and contains(Object o) methods will operate based on o.equals(e). This allows you to do some tricky things with special-purpose comparison objects that aren't necessarily the type of object that are in the collection.

List<Integer> list = Arrays.asList(20, 30, 40, 50, 100);
boolean moreThan60 = list.contains(new Object() {
    public boolean equals(Object rhs) {
        return ((Integer)rhs) > 60;
    }
});
System.out.println("moreThan60 = " + moreThan60);

Not that this is always recommended, or even a best practice. But it is a neat trick.

Upvotes: 3

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

This isn't correct. The prototypes are:

boolean add(E e)
boolean contains(Object o) 
boolean remove(Object o) 

If you correctly use the interface, you can never add a non-E to a List. You can still call contains and remove with non-E's. Technically, the List is allowed to throw a ClassCastException, but this is marked optional, and I don't know of any classes that do so. It will probably just return false, with the List unchanged.

Upvotes: 0

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

If have an ArrayList<String> and assign it to List<?> list. Should I be able to ask list.contains("it")? It is very useful if I can.

Upvotes: 0

Tom
Tom

Reputation: 45104

Backwards compatibility.

This way, you can still run java < 1.5 code with java1.5

So if you have some legacy code that is something like this

List list = //your favorite implementation
list.add(new Car());
list.add(new MandelbrotFractal());

universe wont implode;

Upvotes: 1

Related Questions