Ideally, it would look like this (the context doesn't matter):
public interface myInterface extends Iterable<Point>, Iterable<Segment> { ... }
But this is not allowed in Java. How can I achieve this behaviour?
Unfortunately you cannot. In Java you cannot have two methods with following signatures:
Iterator<Point> iterator();
Iterator<Segment> iterator();
in one class or interface.
As other said before, this is impossible. Better use delegation instead of multiple implementation like this:
public interface MyInterface {
Iterable<Point> points();
Iterable<Segment> segments();
}
So you can iterate using for:
MyInterface my = ...;
for (Point p : my.points()) {
...
}
for (Segment s : my.segments()) {
...
}
You cannot. Due to type erasure, in the bytecode, and therefore at run time, Iterable<Whatever>
becomes Iterable
.
So, at run time, your class' prototype would be:
public interface myInterface extends Iterable, Iterable { ... }
Considering that, how do you determine what class was meant to be iterated over?
As a possible workaround, you could create interfaces for the iterations you want.
public interface SegmentIterable{
public Iterator<Segment> segmentIterator();
}
public interface PointIterable{
public Iterator<Point> pointIterator();
}
It's not ideal, but would be passable as long as you had a limited number of things you wanted to iterate over.
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