Validated by Amaya

INEW 2338, Advanced Java Study Guide:  Collections

Published November 10, 2004
Revised January 9, 2010 for Amays compatibility
By Richard G. Baldwin

File: Inew2338Sg011.htm


Welcome

The purpose of this series of tutorial lessons is to help you learn the essential topics covered in INEW 2338, Advanced Java.

These lessons provide questions, answers, and explanations designed to help you to understand the essential Java features covered by the Advanced Java course.

The textbook for this course is Advanced Java Internet Applications, Second Edition by Art Gittleman, ISBN 1-57676-096-0.  This study guide is for Chapter 11 in the textbook.

In addition to the textbook, I recommend that you study my extensive collection of online Java tutorial lessons.  Those tutorial lessons are published at http://www.dickbaldwin.com.

For this particular study guide, you should study lessons 1350 through 1380 at the URL given above.



Questions

1.  What output is produced by the following program?

import java.util.TreeSet;
import java.util.Collection;
import java.util.Iterator;

public class Inew2338_160{
  public static void main(String args[]){
    new Worker().doIt();
  }//end main()
}//end class Inew2338_160

class Worker{
  public void doIt(){
    Collection ref = new TreeSet();
    Populator.fillIt(ref);
    Iterator iter = ref.iterator();
    while(iter.hasNext()){
      System.out.print(iter.next());
    }//end while loop
    System.out.println();

  }//end doIt()
}// end class Worker

class Populator{
  public static void fillIt(Collection ref){
    ref.add(new Integer(4));
    ref.add(new Integer(4));
    ref.add(new Integer(3));
    ref.add(new Integer(2));
    ref.add(new Integer(1));
  }//end fillIt()
}//end class populator

Answer and Explanation

2.  What is a collection insofar as Java programming is concerned?  Select one or more answers from the following list.

Answer and Explanation

3.  True or False?  Each of the following classes provides an implementation of one of the interfaces that make up the Java Collections Framework.  If False, which items don't belong in the list.

Answer and Explanation

4.  There are at least three things included in a collections framework.  What are they?

Answer and Explanation

5.  True or false?  As of Java SDK version 1.4.2, the core interfaces in the Java Collections Framework are:

Answer and Explanation

6.  True or false?  The following is a general description of the contract for the add method as declared in the Collection interface.

"Ensures that this collection contains the specified element (optional operation). Returns true if this collection changed as a result of the call. (Returns false if this collection does not permit duplicates and already contains the specified element.)"

Answer and Explanation

7.  True or false?  The following is a general description of the contract for the add method as declared in the Set interface.

"Adds the specified element to this set... If this set already contains the specified element, the new element is added and the call returns false..."

Answer and Explanation

8.  True or false?  The Java Collections Framework includes the following concrete implementation classes.

Answer and Explanation

9.  The first box below contains a Java program.

True or false?  The second box below contains the program output.  (The absolute values may change depending on the speed of the computer, but the relationship between the two values should be approximately as shown.)

import java.util.*;

public class Inew2338_162{
  public static void main(String args[]){
    new Worker().doIt();
  }//end main()
}//end class Inew2338_162

class Worker{
  public void doIt(){
    int size = 500000;
    //Create a TreeSet object
    Collection aTree = new TreeSet();

    //Populate the TreeSet object with random
    // values.  The add() method for a set
    // rejects duplicates.
    Random rnGen = new Random();
    for(int ct = 0; ct < size; ct++){
      aTree.add(new Double(rnGen.nextDouble()));
    }//end for loop

    //Create and populate an ArrayList object
    // with the same random values
    Collection aList = new ArrayList(aTree);

    //Extract a value near the center of the
    // ArrayList object to use as a test case.
    Object testVal = ((List)aList).get(size/2);

    //Search for the test value in each of the
    // collection objects. Measure and display
    // the time required to perform the search
    // in each case.
    long start = new Date().getTime();
    boolean found = aList.contains(testVal);
    long stop = new Date().getTime();
    System.out.println(
                   found + " " + (stop - start));

    start = new Date().getTime();
    for(int x = 0; x < 10000; x++){
      found = aTree.contains(testVal);
    }//end for loop
    stop = new Date().getTime();
    System.out.println(
                   found + " " + (stop - start));

  }//end doIt()
}// end class Worker

ArrayList: 20
TreeSet: 170

Answer and Explanation

10.  What output is produced by the following program?

import java.util.TreeSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class Inew2338_164{
  public static void main(String args[]){
    new Worker().doIt();
  }//end main()
}//end class Inew2338_164

class Worker{
  public void doIt(){
    Collection ref = new TreeSet();
    Populator.fillIt(ref);
    Iterator iter = ref.iterator();
    while(iter.hasNext()){
      System.out.print(iter.next());
    }//end while loop
    System.out.print(" ");

    ref = new ArrayList();
    Populator.fillIt(ref);
    iter = ref.iterator();
    while(iter.hasNext()){
      System.out.print(iter.next());
    }//end while loop
    System.out.println();
  }//end doIt()
}// end class Worker

class Populator{
  public static void fillIt(
                       Collection ref){
    ref.add(new Integer(4));
    ref.add(new Integer(4));
    ref.add(new Integer(3));
    ref.add(new Integer(2));
    ref.add(new Integer(1));
  }//end fillIt()
}//end class populator

Answer and Explanation

11.  True or false?  The TreeSet class is a direct implementation of the Collection interface.

Answer and Explanation

12.  True or false?  An ordered collection is not the same as a sorted collection.  The fact that the collection is sorted derives from the fact that each element in the collection has a specific position specified by an index.  In an ordered collection, the position of each element is determined by its value relative to the values of its predecessors and successors.

Answer and Explanation

13.  What output is produced by the following program?

import java.util.*;

public class Inew2338_166{
  public static void main(String args[]){
    new Worker().doIt();
  }//end main()
}//end class Inew2338_166

class Worker{
  public void doIt(){
    Iterator iter;
    Collection ref;

    ref = new ArrayList();
    Populator.fillIt(ref);
    iter = ref.iterator();
    while(iter.hasNext()){
      System.out.print(iter.next());
    }//end while loop
    System.out.println();
  }//end doIt()
}// end class Worker

class Populator{
  public static void fillIt(Collection ref){
    ref.add(0,new MyClass(4));
    ref.add(1,new MyClass(4));
    ref.add(2,new MyClass(3));
    ref.add(3,new MyClass(2));
    ref.add(4,new MyClass(1));
  }//end fillIt()
}//end class populator

class MyClass{
  int data;

  MyClass(){
    data = 0;
  }//end noarg constructor

  MyClass(int data){
    this.data = data;
  }//end parameterized constructor

  public String toString(){
    return "" + data;
  }//end overridden toString()

}//end MyClass

Answer and Explanation

14.  What output is produced by the following program?

import java.util.*;

public class Inew2338_168{
  public static void main(String args[]){
    new Worker().doIt();
  }//end main()
}//end class Inew2338_168

class Worker{
  public void doIt(){
    Iterator iter;
    Collection ref;

    ref = new TreeSet();
    Populator.fillIt(ref);
    iter = ref.iterator();
    while(iter.hasNext()){
      System.out.print(iter.next());
    }//end while loop
    System.out.println();

  }//end doIt()
}// end class Worker

class Populator{
  public static void fillIt(Collection ref){
    ref.add(new MyClass(4));
    ref.add(new MyClass(4));
    ref.add(new MyClass(3));
    ref.add(new MyClass(2));
    ref.add(new MyClass(1));
  }//end fillIt()
}//end class populator

class MyClass{
  int data;

  MyClass(){
    data = 0;
  }//end noarg constructor

  MyClass(int data){
    this.data = data;
  }//end parameterized constructor

  public String toString(){
    return "" + data;
  }//end overridden toString()

}//end MyClass

Answer and Explanation

15.  What output is produced by the following program?

import java.util.*;
import java.io.Serializable;

public class Inew2338_170{
  public static void main(String args[]){
    new Worker().doIt();
  }//end main()
}//end class Inew2338_170

class Worker{
  public void doIt(){
    Iterator iter;
    Collection ref;
    System.out.println("Natural ordering");
    ref = new TreeSet();
    Populator.fillIt(ref);
    iter = ref.iterator();
    while(iter.hasNext()){
      System.out.print(iter.next() + " ");
    }//end while loop
    System.out.println();

    System.out.println("Comparator in use");
    ref = new TreeSet(new TheComparator());
    Populator.fillIt(ref);
    iter = ref.iterator();
    while(iter.hasNext()){
      System.out.print(iter.next() + " ");
    }//end while loop
    System.out.println();

  }//end doIt()
}// end class Worker

class Populator{
  public static void fillIt(Collection ref){
    ref.add("Joe");
    ref.add("Bill");
    ref.add("Tom");
    ref.add("JOE");
    ref.add("BILL");
    ref.add("TOM");
  }//end fillIt()
}//end class populator

class TheComparator
              implements Comparator,Serializable{

  public int compare(Object o1,Object o2){
    if(!(o1 instanceof String))
        throw new ClassCastException();
    if(!(o2 instanceof String))
        throw new ClassCastException();

    //Do an upper-case comparison
    int result =((String)o1).toUpperCase().
                          compareTo(((String)o2).
                                  toUpperCase());
    return result;
  }//end compare()

}//end class TheComparator

Answer and Explanation

16.  What output is produced by the following program?

import java.util.*;
import java.io.Serializable;

public class Inew2338_172{
  public static void main(String args[]){
    new Worker().doIt();
  }//end main()
}//end class Inew2338_172

class Worker{
  public void doIt(){
    Iterator iter;
    Collection ref;
    Object[] array;

    ref = new Vector();
    Populator.fillIt(ref);
    iter = ref.iterator();
    System.out.println("Collection data");
    while(iter.hasNext()){
      System.out.print(iter.next() + " ");
    }//end while loop
    System.out.println();

    array = ref.toArray();
    System.out.println("Raw array data");
    display(array);

    //Sort the array into natural order
    // and display it.
    Arrays.sort(array);
    System.out.println("Natural order sorted " +
                                   "array data");
    display(array);

    //Sort the array into custom order
    // and display it.
    Arrays.sort(
           array, new TheComparator());
    System.out.println("Custom order sorted " +
                                   "array data");
    display(array);

    iter = ref.iterator();
    System.out.println("Collection data");
    while(iter.hasNext()){
      System.out.print(iter.next() + " ");
    }//end while loop
    System.out.println();

  }//end doIt()

  static void display(Object[] array){
    for(int i = 0; i < array.length;i++){
      System.out.print(array[i] + " ");
    }//end for loop
    System.out.println();
  }//end display()
}// end class Worker

class Populator{
  public static void fillIt(Collection ref){
    ref.add("Joe");
    ref.add("Bill");
    ref.add("Tom");
    ref.add("JOE");
    ref.add("BILL");
    ref.add("TOM");
  }//end fillIt()
}//end class populator

class TheComparator
    implements Comparator,Serializable{

  public int compare(Object o1,Object o2){
    if(!(o1 instanceof String))
        throw new ClassCastException();
    if(!(o2 instanceof String))
        throw new ClassCastException();

    int result = ((String)o1).compareTo(
                                   ((String)o2));
    return result*(-1);
  }//end compare()
}//end class TheComparator

Answer and Explanation

17.  What output is produced by the following program?

import java.util.*;
import java.io.Serializable;

public class Inew2338_174{
  public static void main(String args[]){
    new Worker().doIt();
  }//end main()
}//end class Inew2338_174

class Worker{
  public void doIt(){
    Iterator iter;
    Collection ref;

    ref = new LinkedList();
    Populator.fillIt(ref);
    Collections.sort(
                 (List)ref, new TheComparator());
    iter = ref.iterator();
    while(iter.hasNext()){
      System.out.print(iter.next() + " ");
    }//end while loop
    System.out.println();

  }//end doIt()
}// end class Worker

class Populator{
  public static void fillIt(Collection ref){
    ref.add("Joe");
    ref.add("Bill");
    ref.add("Tom");
    ref.add("JOE");
    ref.add("BILL");
    ref.add("TOM");
  }//end fillIt()
}//end class populator

class TheComparator
    implements Comparator,Serializable{

  public int compare(Object o1,Object o2){
    if(!(o1 instanceof String))
        throw new ClassCastException();
    if(!(o2 instanceof String))
        throw new ClassCastException();

    int result = ((String)o1).
                         compareTo(((String)o2));
    return result*(-1);
  }//end compare()
}//end class TheComparator

Answer and Explanation

18.  What output is produced by the following program (select one or more answers)?

import java.util.*;

public class Inew2338_176{
  public static void main(String args[]){
    new Worker().doIt();
  }//end main()
}//end class Inew2338_176

class Worker{
  public void doIt(){
    Iterator iter;
    Collection ref;

    ref = new ArrayList();
    Populator.fillIt(ref);
    iter = ref.iterator();
    while(iter.hasNext()){
      System.out.print(iter.next() + " ");
    }//end while loop
    System.out.println();

    Collections.reverse((List)ref);
    iter = ref.iterator();
    while(iter.hasNext()){
      System.out.print(iter.next() + " ");
    }//end while loop
    System.out.println();

    Comparator aComparator
                    = Collections.reverseOrder();
    Collections.sort((List)ref, aComparator);
    iter = ref.iterator();
    while(iter.hasNext()){
      System.out.print(iter.next() + " ");
    }//end while loop
    System.out.println();

  }//end doIt()
}// end class Worker

class Populator{
  public static void fillIt(Collection ref){
    ref.add("Joe");
    ref.add("Bill");
    ref.add("Tom");
    ref.add("JOE");
    ref.add("BILL");
    ref.add("TOM");
  }//end fillIt()
}//end class populator

Answer and Explanation

19.  What output is produced by the following program?

import java.util.*;
import javax.swing.*;

public class Inew2338_178{
  public static void main(String args[]){
    new Worker().doIt();
  }//end main()
}//end class Inew2338_178
//=============================================//

class Worker{
  public void doIt(){
    Collection ref;

    //Create, populate, and display the
    // contents of a collection
    ref = new LinkedList();
    Populator.fillIt(ref);
    System.out.println("Collection contents");
    showCollection(ref);

    //Get collection contents into the
    // array and display the new
    // contents of the array.
    Object[] array = ref.toArray();
    System.out.println("New array contents");
    showArray(array);

    //Modify a property of an object
    // referred to by one of the
    // elements in the array. Display
    // array contents after
    // modification
    System.out.println(
                      "Modified array contents");
    ((JComponent)array[0]).setToolTipText("XX");
    showArray(array);

    //Display the contents of the
    // collection
    System.out.println("Collection contents");
    showCollection(ref);
  }//end doIt()
//---------------------------------------------//

  //Utility method for displaying
  // array contents
  void showArray(Object[] array){
    for(int i = 0; i < array.length;i++){
      if(array[i] == null){
        System.out.print("null ");
      }else{
        System.out.print(((JComponent)array[i]).
                         getToolTipText() + " ");
      }//end else
    }//end for loop
    System.out.println();
  }//end showArray()
//---------------------------------------------//

  //Utility method for displaying
  // collection contents
  void showCollection(Collection ref){
    Iterator iter = ref.iterator();
    while(iter.hasNext()){
      System.out.print(((JComponent)iter.next()).
                         getToolTipText() + " ");
    }//end while loop
    System.out.println();
  }//end showCollection
}// end class Worker
//=============================================//

class Populator{
  public static void fillIt(Collection ref){
    ref.add(new JButton());
    ref.add(new JButton());
    ref.add(new JLabel());
    ref.add(new JButton());
    ref.add(new JButton());
    ref.add(new JLabel());

    Iterator iter = ref.iterator();
    int cnt = 0;
    JComponent refVar;
    while(iter.hasNext()){
      refVar = (JComponent)iter.next();
      if(refVar instanceof JButton){
        refVar.setToolTipText("B"+cnt++);
      }else{
        refVar.setToolTipText("L" + cnt++);
      }//end else
    }//end while loop

  }//end fillIt()
}//end class populator

Answer and Explanation

20.  What output is produced by the following program?

import java.util.*;
import javax.swing.*;

public class Inew2338_180{
  public static void main(String args[]){
    new Worker().doIt();
  }//end main()
}//end class Inew2338_180
//=============================================//

class Worker{
  public void doIt(){
    Collection ref;

    //Create, populate, and display
    // the contents of an array
    JComponent[] array = new JComponent[8];
    for(int cnt=0;cnt<8;cnt++){
      array[cnt] = new JButton();
      array[cnt].setToolTipText("" + (cnt+10));
    }//end for loop
    System.out.println();
    showArray(array,"Original array contents");


    //Create, populate, and display the
    // contents of a collection
    ref = new LinkedList();
    Populator.fillIt(ref);
    showCollection(ref,"Collection contents");

    //Get collection contents into the
    // array and display the new
    // contents of the array.
    array = (JComponent[])ref.toArray(array);
    showArray(array,"New array contents");

    //Modify a property of an object
    // referred to by one of the
    // elements in the array. Display
    // array contents after
    // modification
    ((JComponent)array[0]).setToolTipText("XX");
    showArray(array,"Modified array contents");

    //Display the contents of the
    // collection
    showCollection(ref,"Collection contents");
  }//end doIt()
//---------------------------------------------//

  //Utility method for displaying
  // array contents
  void showArray(Object[] array,String title){
    System.out.println(title);
    for(int i = 0; i < array.length;i++){
      if(array[i] == null){
        System.out.print("null ");
      }else{
        System.out.print(((JComponent)array[i]).
                         getToolTipText() + " ");
      }//end else
    }//end for loop
    System.out.println();
  }//end showArray()
//---------------------------------------------//

  //Utility method for displaying
  // collection contents
  void showCollection(Collection ref,
                                   String title){
    System.out.println(title);
    Iterator iter = ref.iterator();
    while(iter.hasNext()){
      System.out.print(((JComponent)iter.next()).
                         getToolTipText() + " ");
    }//end while loop
    System.out.println();
  }//end showCollection
}// end class Worker
//=============================================//

class Populator{
  public static void fillIt(Collection ref){
    ref.add(new JButton());
    ref.add(new JButton());
    ref.add(new JLabel());
    ref.add(new JButton());
    ref.add(new JButton());
    ref.add(new JLabel());

    Iterator iter = ref.iterator();
    int cnt = 0;
    JComponent refVar;
    while(iter.hasNext()){
      refVar = (JComponent)iter.next();
      if(refVar instanceof JButton){
        refVar.setToolTipText("B"+cnt++);
      }else{
        refVar.setToolTipText("L" + cnt++);
      }//end else
    }//end while loop

  }//end fillIt()
}//end class populator

Answer and Explanation



Copyright 2004, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two.  He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Java Programming Tutorials, which have gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

Baldwin@DickBaldwin.com


Answers and Explanations


Answer  20

This program produces the following output:

Original array contents
10 11 12 13 14 15 16 17
Collection contents
B0 B1 L2 B3 B4 L5
New array contents
B0 B1 L2 B3 B4 L5 null 17
Modified array contents
XX B1 L2 B3 B4 L5 null 17
Collection contents
XX B1 L2 B3 B4 L5

Explanation 20

The main purpose of this program is to demonstrate that an array created by the toArray method contains copies of the references contained in the original collection. Using those copies to mutate the objects causes the original objects referred to by the collection to be mutated. In addition, this program also illustrates the complex form of toArray that allows the programmer to provide the array that is to be populated by the toArray method.

You can learn more about this topic in lesson 1380 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 20
 


Answer 1 9

This program produces the following output:

Collection contents
B0 B1 L2 B3 B4 L5
New array contents
B0 B1 L2 B3 B4 L5
Modified array contents
XX B1 L2 B3 B4 L5
Collection contents
XX B1 L2 B3 B4 L5

Explanation 19

The main purpose of this program is to demonstrate that an array created by the toArray method contains copies of the references contained in the original collection.  Using those copies to mutate the objects causes the original objects referred to by the collection to be mutated. The program also illustrates the simple form of the toArray method.

You can learn more about this topic in lesson 1378 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 19


Answer 1 8

This program produces the following output:

Joe Bill Tom JOE BILL TOM
TOM BILL JOE Tom Bill Joe
Tom TOM Joe JOE Bill BILL

Explanation 18

The main purpose of this program is to demonstrate how to use a Comparator created by the reverseOrder method of the Collections class to sort an ArrayList into reverse natural order. The program also shows how to use the reverse method of the Collections class to reverse the order of the elements in a list.

You can learn more about this topic in lesson 1376 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 18


Answer 1 7

D.  Tom TOM Joe JOE Bill BILL

Explanation 17

The main purpose of this program is to demonstrate how to use the sort method of the Collections class along with a Comparator to cause a LinkedList to be sorted in reverse natural order.
 

You can learn more about this topic in lesson 1374 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 17


Answer 16

This program produces the following output:

Collection data
Joe Bill Tom JOE BILL TOM
Raw array data
Joe Bill Tom JOE BILL TOM
Natural order sorted array data
BILL Bill JOE Joe TOM Tom
Custom order sorted array data
Tom TOM Joe JOE Bill BILL
Collection data
Joe Bill Tom JOE BILL TOM

Explanation 16

The main purpose of this program is to demonstrate how to create an array from a Vector and how to use a Comparator to cause the array to be sorted both in natural order and also in custom order.

You can learn more about this topic in lessons 1370 and 1372 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 16


Answer 15

F.  None of the above.

Explanation 15

The output from the program is a shown below:

Natural ordering
BILL Bill JOE Joe TOM Tom
Comparator in use
Bill Joe Tom

The main purpose of this program is to demonstrate the use of a Comparator to eliminate the effect of case when sorting String objects.

You can learn more about this topic in lessons 1366 and 1368 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 15


Answer 14

B.  Runtime Error

Explanation 14

To make a long story short, the program throws a ClassCastException because the objects being added to the TreeSet object do not implement the Comparable interface (or the Comparator interface). Therefore, they cannot be compared for the elimination of duplicate elements or to arrange the elements into the natural ordering.

You can learn more about this topic in lesson 1364 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 14


Answer 13

A.  Compiler Error

Explanation 13

The compiler error was caused by the code shown below. 

  public static void fillIt(Collection ref){
    ref.add(0,new MyClass(4));

Listing 2

The problem is that the method named fillIt receives a reference to an object of the ArrayList class as the interface type Collection, and attempts to invoke the following overloaded method on that reference:

add(int index, Object element)

The ArrayList class implements both the Collection interface and the List interface.  List is a subinterface of Collection.  The List interface declares the following overloaded versions of the add method:

add(Object o)
add(int index, Object element)

The second of these two methods is unknown to the Collection interface.  The Collection interface declares only the first version of the add method shown above.

This is the result of specialization.  A List object is a more-specialized collection than a Collection object.

Therefore, the version of the add method that requires two parameter cannot be invoked on a reference to an ArrayList object when that object is treated as the generic type Collection.  It is necessary to downcast the reference in order to invoke that version of the add method.

You can learn more about this topic in lesson 1362 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 13


Answer 12

False.

Explanation 12

The conditions in the statement are reversed.  The true statement is:

An ordered collection is not the same as a sorted collection.  The fact that the collection is ordered derives from the fact that each element in the collection has a specific position specified by an index.  In a sorted collection, the position of each element is determined by its value relative to the values of its predecessors and successors.

You can learn more about this topic in lesson 1360 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 12


Answer 11

False.

Explanation 11

The TreeSet class is not a direct implementation of the Collection interface.  Rather, the TreeSet class is a direct implementation of the SortedSet interface.  The SortedSet interface extends the Set interface, and the Set interface extends the Collection interface.

You can learn more about this topic in lesson 1360 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 11


Answer 10

E.  1234 44321

Explanation 10

This program illustrates the basic purpose of the core collection interfaces in the Java Collections Framework.  That purpose is to allow collections to be manipulated without regard for how the collections are implemented.

For example, there is more than one way to implement a list.  Two common ways involve arrays and linked structures.  If two lists are implemented in different ways, but both satisfy the requirements of the core collection interfaces, they can each be manipulated the same way regardless of the details of their implementation.

A collection of type TreeSet and a collection of type ArrayList are instantiated in the program.  Each of the collections is viewed as being of the interface type Collection.  A method named add is used to attempt to populate each collection with the same values.

The behavior of the add method is appropriate, and different in each of the two cases, with the final contents of each collection being determined by the respective behavior of the add method for that type of collection.

The important point is that although the fillIt method invokes the same method name (add) on each of the collection objects, the behavior of that method is different in each case.  In both cases, the behavior is appropriate for the underlying data structure.  Furthermore, the underlying data structure isn't even known to the fillIt method.

You can learn more about this topic in lesson 1358 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 10


Answer 9

False.

Explanation 9

The relationship that is shown between the two values is backwards.  The following is closer to what should be expected from this program.

ArrayList: 170
TreeSet: 20

You can safely invoke the contains method on any object instantiated from a class that properly implements the Collection interface, even if you don't know the actual type of the collection object.

The manner in which the search will be performed will probably differ from one concrete implementation of the interface to the next.  For example, a TreeSet object will perform the search very rapidly with a time cost of only log(n) where n is the number of elements.  On the other hand, for the same number of elements, because of a different underlying data structure, a search on an ArrayList object will probably require more time than a search on a TreeSet object.  As the number of elements increases, the difference in time cost between the two will also increase.

You can learn more about this topic in lesson 1356 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 9


Answer 8

False.

Explanation 8

Set is not a class.  It is an interface.

You can learn more about this topic in lesson 1354 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 8


Answer 7

False.

Explanation 7

The following is a general description of the contract for the add method as declared in the Set interface.

"Adds the specified element to this set if it is not already present... If this set already contains the specified element, the call leaves this set unchanged and returns false... this ensures that sets never contain duplicate elements."

You can learn more about this topic in lesson 1354 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 7


Answer 6

True.

Explanation 6

The contract for the add method of the Collection interface is rather general in nature, and applies to all classes that implement the interface.

You can learn more about this topic in lesson 1354 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 6


Answer 5

False.

Explanation 5

Vector is not an interface.  It is a class.
 

You can learn more about this topic in lesson 1354 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 5


Answer 4

At least three things are included in a collections framework:

Explanation 4

You can learn more about this topic in lesson 1354 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 4


Answer 3

Hopefully your answer was False, but even so, that isn't the complete answer.

Explanation 3

Iterator is not a class.  It is an interface.

You may also have wondered if the classes named Attributes and RenderingHints belong on the list.  (Note that I didn't restrict the above list to only those classes that might be considered part of the framework.)

While these two classes are not really a part of the core Java Collections Framework, they do implement interfaces that are part of the framework.

The RenderingHints class implements the Map interface and is used in conjunction with the Graphics2D class.  The Attributes class also implements the Map interface

You can learn more about this topic in lesson 1352 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 3


 

Answer 2

If you answered A, you are probably on the wrong website.  If you answered both B and C, then you are correct.

Explanation 2

A collection is an object that groups multiple elements into a single unit.

Collection is also the name of a Java interface.

You can learn more about this topic in lesson 1352 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 2


Answer 1

E. 1234

Explanation 1

The Collection object in this problem is an object of the class TreeSet.  The TreeSet class implements the Set interface, the SortedSet interface, and some other interfaces as well.

According to the contract of the collections framework, classes that implement the Set interface must not allow duplicate elements.  A class that implement the SortedSet interface "further guarantees that its iterator will traverse the set in ascending element order, sorted according to the natural ordering of its elements (see Comparable), or by a Comparator provided at sorted set creation time."

You can learn more about this topic in lesson 1350 at http://www.dickbaldwin.com/tocadv.htm.

You might also want go to Google and search for the following keywords:

This might help you to locate some of Prof. Baldwin's publications on these topics that were not included in the lessons listed earlier.  Go to the last page of the Google results and click on the link that reads repeat the search with the omitted results included to make certain that Google didn't omit any links that might be useful to you.

Back to Question 1


Copyright 2004, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two.  He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Java Programming Tutorials, which have gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

Baldwin@DickBaldwin.com

-end-