Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
- Question: Which two of the following interfaces are at the top of the hierarchies in the Java Collections Framework?
Answer:
Set
Map
Queue
SortedMap
Collection
List
Map
andCollection
are at the top of the hierarchies in the Java Collections Framework.Set
,Queue
, andList
are subinterfaces ofCollection
.SortedMap
is a subinterface ofMap
.- Question: Which of the following interfaces does not allow duplicate objects?
Answer:
Queue
Set
List
Set
does not allow duplicate objects.- Question: In order for objects in a
List
to be sorted, those objects must implement which interface and method? Answer: The objects must implement theComparable
interface and itscompareTo
method.- Question: True or false: The
element
method alters the contents of aQueue
. Answer: False. Theelement
method retrieves, but does not remove, the head of thequeue
.
- Exercise: Write a method with the signature:
that (1) traverses through the elements inpublic Collection<String> filter(Collection<String> c)c
using anIterator
, (2) checks whether each element meets a certain condition (in a separate methodcondition
which you do not need to define right now), and (3) if the object meets the condition, adds it to the newCollection
to return. The method should not modify theCollection c
. Design the method to work on any collection ofString
s. Only thecondition
method should have application-specific code; we will define this method as part of an application in the exercises for the Implementations lesson. Answer:public Collection<String> filter(Collection<String> c) { Collection<String> filteredCollection = new ArrayList<String>(); for (Iterator<String> i = c.iterator(); i.hasNext(); ) { String s = (String) i.next(); if (condition(s)) { filteredCollection.add(s); } } return filteredCollection; }- Exercise: Write a method with the signature:
that returns a newpublic List<Integer> reverse(List<Integer> orginalList)List
that contains the sameInteger
objects as theoriginalList
argument, but in reverse order. The method should not modify theorginalList
object. Answer:public List<Integer> reverse(List<Integer> orginalList) { Listreversed = new LinkedList<Integer>(); for (int i = orginalList.size() - 1; i >= 0; i--) { reversed.add(orginalList.get(i)); } return reversed; }
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.