So I have a class I have made which I wanted to be able to sort. To do so I simply had it implement the collection interface so it can be used in the Collections class.
Now I have noticed that the class itself is just a hop, skip, and a jump away from a ListIterator and it would be nice to have it implement that interface as well (looking into the future on this one). There is one problem, though, and that is that there is a method conflict between the Collection interface and ListIterator interface:
// from the Collection interface:
public boolean add(E someElement);
// from the ListIterator interface:
public void add(E someElement);
Is it possible to have one class conform to both interfaces? If not, does that mean that these two interfaces are mutually exclusive?
The ListIterator interface of the Java collections framework provides the functionality to access elements of a list. It is bidirectional. This means it allows us to iterate elements of a list in both the direction. It extends the Iterator interface.
Iterators are used in Collection framework in Java to retrieve elements one by one. It can be applied to any Collection object. By using Iterator, we can perform both read and remove operations.
A ListIterator gives us the ability to access the collection in either forward or backward direction and lets you modify an element. Otherwise, ListIterator is used like an Iterator. If you don’t want to modify the contents of collection or want to obtain the elements in reverse order, the For-Each version is more convenient.
Which implementation of Iterator can traverse a collection back and forth? Iterator can only traverse forward while ListIterator traverses both forward and backward. ListIterator can help replace an element, while Iterator cannot. 3. The interface Comparable contains the method ___________
Yes, unfortunately, they are mutually exclusive.
When you create an (abstract) class that tries to implement both, you'll get a compiler error.
Main.java:16: error: types ListIterator and Collection are incompatible; both define add(java.lang.Object), but with unrelated return types
abstract class Foo implements Collection, ListIterator
You are right, you can't implement both. But to be honest why do you want to do that?
If you need to expose a ListIterator
, why don't you add a method that returns one?
List
which extends Collection
for instance doesn't extend ListIterator
, it has a method called listIterator
that returns the iterator.
ListIterator<E> listIterator();
Keep something in mind, a Collection
is not an Iterator
, a Collection
is an Iterable
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With