Java Reference
In-Depth Information
/** The scrolling list */
protected
protected
java
.
awt
.
List
visList
=
new
new
java
.
awt
.
List
();
/** Add one (new) Person to the list, keeping the list sorted. */
protected
protected
void
void
add
(
Person p
) {
String lastName
=
p
.
getLastName
();
int
int
i
;
// Find in "i" the position in the list where to insert this person
for
for
(
i
=
0
;
i
<
usrList
.
size
();
i
++)
iif
(
lastName
.
compareTo
((
usrList
.
get
(
i
)).
getLastName
()) <=
0
)
break
break
;
// If we don't break, will insert at end of list.
usrList
.
add
(
i
,
p
);
// Now insert them in the scrolling list, in the same position.
visList
.
add
(
p
.
getName
(),
i
);
visList
.
select
(
i
);
// ensure current
}
}
This code uses the
String
class
compareTo(String)
routine.
WARNING
This code uses a linear search, which was fine for the original application, but could get
very slow on large lists (it is
O(n)
). You'd need to use hashing or a binary search to find
where to put the values on large lists.
If I were writing this code today, I might well use a
TreeSet
(which keeps objects in order)
or a
TreeMap
(which keeps the keys in order and maps from keys to values; the keys would
be the name and the values would be the
Person
objects). Both insert the objects into a tree
in the correct order, so an
Iterator
that traverses the tree always returns the objects in sor-
ted order. In addition, they have methods such as
headSet()
and
headMap()
, which give a
new
Set
or
Map
of objects of the same class, containing the objects lexically before a given
value. The
tailSet()
and
tailMap()
methods, similarly, return objects greater than a given
value, and
subSet()
and
subMap()
return a range. The
first()
and
last()
methods re-