Re: looping through a list, starting at 1
Andreas Leitgeb wrote:
Lew wrote:
Andreas Leitgeb wrote:
Lew wrote:
Volker Borchert wrote:
if (l instanceof RandomAccess) {
Tests on type like this are an antipattern.
Are marker-interfaces (which RandomAccess is, iirc) already an
antipattern, or is there a different way to check for them, [...]
With generics you can use type intersections so that something has to be
both 'List' and 'RandomAccess' (again, say) even to reach the call or th=
e
class or whatever.
Interesting stuff! (but still falls a bit short):
--- snip SSCCE Test.java ---
import java.util.*;
public class Test {
public static void main(String[] args) {
method( new ArrayList(42) );
method( new Vector(42) );
//method( new LinkedList(42) ); // would error: good!
}
public static <T extends List,RandomAccess> T method(T raAcList) {
return raAcList;
}
//Provide a fallback overload for all Lists: doesn't compile
// public static <T extends List> T method(T anyList) {
// return anyList;
// }
You cannot have two erasure-equivalent methods in the same class, so that's=
why both won't co-exist.
The generics trick is suitable when you want to insist that the argument be=
of the particular type, not when you want to bifurcate as you indicated. =
It seems as though perhaps you are in a situation where you want to fork on=
the type at run-time, but I am not convinced yet.
The object is asked at runtime if it is a RandomAccess, and
either way correct (hope so) and appropriate code is executed
for the object. It's not principially different from asking
a (list-)object if it is empty(), and do something appropriate
in each case.
It is different, inherently so, in that type assertions normally should be =
done at compile time, and are less expensive to aver at that time, but list=
emptiness is inherently a run-time issue, being based on data and not the =
program's own types.
I only wished to point out a general principle here.
Thanks for pointing out the trick with generics, even though
it doesn't yet fully work. I hadn't thought of that, and might
run into a situation where it could prove useful.
It does "fully work", if the problem is fully thought out.
--
Lew