Re: looping through a list, starting at 1
On Thursday, August 11, 2011 4:37:02 AM UTC-7, Andreas Leitgeb wrote:
Arved Sandstrom <asandstr...@eastlink.ca> wrote:
On 11-08-10 07:50 PM, Andreas Leitgeb wrote:
How would I write a method (overload) that would only take an
object if it is both List and RandomAccess? (Afaik: no way, but
I might perhaps miss something.)
Pretty much in the standard way, which would take advantage of the
marker interface in a way suggested by Bloch: you create an interface
that extends List and RandomAccess, and concrete classes implement that=
..
That's just not applicable to the Collections framework as it is:
We've all been taught to use interface-names for the static type
of variables to hold whatever concrete implementation:
ArrayList l = new ArrayList(); // discouraged
List l = new ArrayList(); // encouraged
No, that's not what we've been taught. We've been taught to use the type t=
hat most generally allows the compiler to enforce the specific contract we =
need. That does not always mean use the interface (not "names"), nor the m=
ost general interface. Sometimes you do want to peg a variable or return t=
ype to a specific implementation, or a specific interface, or an interface =
that mixes in two parent interfaces per Bloch. Don't make a religion of "u=
se the (most general) interface" - the actual principle is "use the type th=
at guarantees your contract". So 'RandomList extends List, RandomAccess' i=
s perfectly acceptable.
....
That's of course just rambling. Marker-interfaces just aren't used that
way, but instead they are always checked at runtime. So, either Marker-
Nope. Their value is when they're checked *at compile time*.
It's the use at run time that is suspect.
interfaces (such as RandomAccess) are an anti-pattern themselves, or
that pattern is one declared exception to the "instanceof"-red flag.
Marker interfaces are not an antipattern. Use of 'instanceof' is, often.
Use marker interfaces for *compile time* safety.
--
Lew