Generalization List Interface ... newb question

The List interface is as follows:

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

Why aren't methods added as follows written in?

 public boolean add(E e) public boolean remove(E e) public boolean contains(E e) 
+4
source share
4 answers

The add method is add (E e) , so everything is correct in this regard with the world.

remove (Object o) and contains (Object o) will act based on o.equals(e) . This allows you to do some complex things with special purpose comparison objects, which are not necessarily the type of object that is 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 it is always recommended, or even best practice. But this is a neat trick.

+3
source

Backward compatibility.

So you can still run java <1.5 with java1.5

So, if you have legacy code, something like this

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

The universe will not be destroyed;

+1
source

This is not true. Prototypes:

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

If you use the interface correctly, you can never add non-E to the list. You can still call cells and delete using non-E. Technically, the List is allowed to throw a ClassCastException, but it is marked as optional, and I do not know about any classes that do this. It will probably just return false if the list does not change.

0
source

If there is an ArrayList<String> and assign it to List<?> list . Should I ask list.contains("it") ? This is very helpful if I can.

0
source

Source: https://habr.com/ru/post/1308846/


All Articles