Java Reference
In-Depth Information
if
((newPosition >= 1) && (newPosition <= list.size() + 1))
list.add(newPosition - 1, newEntry);
else
isSuccessful =
false
;
return
isSuccessful;
}
// end add
13.19
The method
replace
.
The method
replace
has an implementation similar to the one you just saw.
It uses the statement
list.set(givenPosition - 1, newEntry);
to replace a designated entry in the list.
public boolean
replace(
int
givenPosition, T newEntry)
{
boolean
isSuccessful =
true
;
if
((givenPosition >= 1) && (givenPosition <= list.size()))
{
assert
!isEmpty();
list.set(givenPosition - 1, newEntry);
}
else
isSuccessful =
false
;
return
isSuccessful;
}
// end replace
13.20
The method
toArray
.
We call
Vector
's method
toArray
within the definition of
toArray
for a list.
The only worry is to take care of the unchecked cast of an array of type
Object[]
to an array of
type
T[]
. Thus, the method has the following definition:
public
T[] toArray()
{
@SuppressWarnings(“unchecked”);
T[] result = (T[])list.toArray();
return
result;
}
// end toArray
13.21
The method
remove
.
Our method
remove
uses
Vector
's method
remove
, which returns the object
it removes from the vector. Like
add
,
Vector
's
remove
throws an exception when given an illegal
position. Our method, however, will return
null
in this case. Thus, our
remove
method has the
following implementation:
public
T remove(
int
givenPosition)
{
T result =
null
;
// return value
if
((givenPosition >= 1) && (givenPosition <= list.size()))
{
assert
!isEmpty();
result = list.remove(givenPosition - 1);
}
// end if
return
result;
}
// end remove
13.22
The method
getEntry
.
The method
getEntry
has an implementation similar to that of
remove
. It
uses the expression
list.get(givenPosition - 1);
to retrieve a particular entry from the list.