Java Reference
In-Depth Information
Display 16.4
Selected Methods in the
List<T>
Interface
(part 3 of 3)
public
int
lastIndexOf(Object target)
Returns the index of the last element that is equal to
target
. Uses the method
equals
of the
object
target
to test for equality. Returns
1
if target is not found.
public
List<T> subList(int fromIndex, int toIndex)
Returns a
view
of the elements at locations
fromIndex
to
toIndex
of the calling object; the
object at
fromIndex
is included; the object, if any, at
toIndex
is not included. The
view
uses ref-
erences into the calling object; so, changing the
view
can change the calling object. The returned
object will be of type
List<T>
but need not be of the same type as the calling object. Returns an
empty
List<T>
if
fromIndex
equals
toIndex
.
ListIterator<T> listIterator( )
Returns a list iterator for the calling object. (Iterators are discussed in Section 16.3.)
ListIterator<T> listIterator(int index)
Returns a list iterator for the calling object starting at
index
. The first element to be returned by
the iterator is the one at
index
. (Iterators are discussed in Section 16.3.)
Collection Interfaces
The primary interfaces for collection classes are the
Collection<T>
,
Set<T>
, and
List<T>
interfaces. Both the
Set<T>
and the
List<T>
interfaces are derived from the
Collection<T>
interface. The
Set<T>
interface is for collections that do not allow repetition of elements and
do not impose an order on their elements. The
List<T>
interface is for collections that do allow
repetition of elements and do impose an order on their elements.
For-Each Loops
You can use a for-each loop with any of the collections discussed in this chapter.
PITFALL: Optional Operations
What is the point of an optional method heading in an interface? The whole point of
an interface is to specify what methods can be used with an object of the interface type
so that you can write code for an arbitrary object of the interface type. The reasoning
behind these optional methods is that they normally would be implemented, but in
unusual situations a programmer may leave them “unsupported.” (The alternative
would be to have two interfaces, one with and one without the optional operations.
Uncharacteristically, Java designers opted for a smaller number of interfaces.) But there
is still more to the story.