The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Collections
Lesson: Implementations

Questions and Exercises: Implementations

Questions

  1. If you need a Set implementation that provides value-ordered iteration, which class should you use?
    • HashSet
    • LinkedHashSet
    • TreeSet
  2. Which of the following classes implements a FIFO Queue?
    • HashSet
    • LinkedList
    • PriorityQueue
    • CopyOnWriteArraySet
  3. Which class do you use to access wrapper implementations?
  4. Which class and static method can you use to convert an array to a List?

Exercises

  1. In the Interfaces exercises, you created a method called filter that (1) traversed through the elements in a Collection using an Iterator, (2) checked whether each String met a certain condition, and (3) if the String met the condition, added it to a new Collection to return.

    We will now use this method in a complete program that tells us which months it is safe to eat oysters (months with names that contain "r"). Following is partial code for that program, with comments where you need to add statements.

    import java.util.Collection;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Iterator;
    import java.text.DateFormatSymbols;
    
    public class OysterMonths {
    
        Collection <String> safeMonths;
    	
        public static void main(String[] args) {
        
          OysterMonths om = new OysterMonths();
          DateFormatSymbols dfs = new DateFormatSymbols();
          String[] monthArray = dfs.getMonths();
    
          /*
    		
          (1)Create a Collection that stores the month names.                
        
          (2)Use the filter method to store in the safeMonths 
              Collection the names of the safe months.
    		
          (3)Print out the names of the safe months.
    		
          */
        }
    	
        public Collection <String> filter
                                     (Collection<String> c) {
    				 
          Collection <String> filteredCollection = 
    		                 new ArrayList<String>();
    
          for (Iterator<String> i = c.iterator();
                                     i.hasNext(); ) {
            String s = i.next();
            if (condition(s)) {
               filteredCollection.add(s);
            }
          }
          return filteredCollection;
        }
    
        public boolean condition(String s) {
          if (s.contains("r")) {
            return true;
          }
          return false;
        }
    }
    
Check your answers. (in the Collections trail)

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.