Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

AhmadLang / Java, How To Program, 2004

.pdf
Скачиваний:
626
Добавлен:
31.05.2015
Размер:
51.82 Mб
Скачать

unmodifiable collections

view

view an array as a List

wrapper class

[Page 955 (continued)]

Self-Review Exercises

19.1 Fill in the blanks in each of the following statements:

a.A(n) __________ is used to walk through a collection and can remove elements from the collection during the iteration.

b.An element in a List can be accessed by using the element's __________.

c.Lists are sometimes called __________.

d.Java classes __________ and __________ provide the capabilities of arraylike data structures that can resize themselves dynamically.

e.If you do not specify a capacity increment, the system will __________ the size of the Vector each time additional capacity is needed.

f.You can use a(n) __________ to create a collection that offers only read-only access to others while allowing readwrite access to yourself.

g.__________ can be used to create stacks, queues, trees and deques (doubleended queues).

h.Algorithm __________ of Collections determines whether two collections have elements in common.

19.2 Determine whether each statement is true or false. If false, explain why.

a.Values of primitive types may be stored directly in a Vector.

b.A Set can contain duplicate values.

c.A Map can contain duplicate keys.

d.A LinkedList can contain duplicate values.

e.Collections is an interface.

f.Iterators can remove elements.

g.With hashing, as the load factor increases, the chance of collisions decreases.

h.A PriorityQueue permits null elements.

[Page 955 (continued)]

Answers to Self-Review Exercises

19.1 a) Iterator. b) index. c) sequences. d) ArrayList, Vector. e) double. f) unmodifiable wrapper. g) LinkedLists. h) disjoint.

[Page 956]

19.2 a. False; a Vector stores only objects. Autoboxing occurs when adding a primitive type to the Vector, which means the primitive type is converted to its corresponding type-wrapper class.

b.False. A Set cannot contain duplicate values.

c.False. A Map cannot contain duplicate keys.

d.True.

e.False. Collections is a class; Collection is an interface.

f.True.

g.False. With hashing, as the load factor increases, there are fewer available slots relative to the total number of slots, so the chance of selecting an occupied slot (a collision) with a hashing operation increases.

h.False. A NullPointerException is thrown if the program attempts to add null to a PriorityQueue.

[Page 956 (continued)]

Exercises

19.3Define each of the following terms:

a.Collection

b.Collections

c.Comparator

d.List

e.load factor

f.collision

g.spacetime trade-off in hashing

h.HashMap

19.4Explain briefly the operation of each of the following methods of class Vector:

a.add

b.insertElementAt

c.set

d.remove

e.removeAllElements

f.removeElementAt

g.firstElement

h.lastElement

i.isEmpty

j. contains

k.indexOf

l.size

m.capacity

19.5Explain why inserting additional elements into a Vector object whose current size is less than its capacity is a relatively fast operation and why inserting additional elements into a Vector object whose current size is at capacity is a relatively slow operation.

19.6By extending class Vector, Java's designers were able to create class Stack quickly. What are the negative aspects of this use of inheritance, particularly for class Stack?

19.7Briefly answer the following questions:

a.What is the primary difference between a Set and a Map?

b.Can a two-dimensional array be passed to Arrays method asList? If yes,

how would an individual element be accessed?

c.What happens when you add a primitive type (e.g., double) value to a collection?

d.Can you print all the elements in a collection without using an Iterator? If yes, how?

[Page 957]

19.8Explain briefly the operation of each of the following Iterator-related methods:

a.iterator

b.hasNext

c.next

19.9Explain briefly the operation of each of the following methods of class HashMap:

a.put

b.get

c.isEmpty

d.containsKey

e.keySet

19.10Determine whether each of the following statements is true or false. If false, explain why.

a.Elements in a Collection must be sorted in ascending order before a binarySearch may be performed.

b.Method first gets the first element in a treeSet.

c.A List created with Arrays method asList is resizable.

d.Class Arrays provides static method sort for sorting array elements.

19.11Explain the operation of each of the following methods of the Properties class:

a.load

b.store

c.getProperty

d.list

19.12Rewrite lines 1726 in Fig. 19.4 to be more concise by using the asList method and the LinkedList constructor that takes a Collection argument.

19.13Write a program that reads in a series of first names and stores them in a LinkedList. Do not store duplicate names. Allow the user to search for a first name.

19.14Modify the program of Fig. 19.20 to count the number of occurrences of each letter rather than of each word. For example, the string "HELLO THERE" contains two Hs, three Es, two Ls, one O, one T and one R. Display the results.

19.15Use a HashMap to create a reusable class for choosing one of the 13 predefined colors

in class Color. The names of the colors should be used as keys, and the predefined

Color objects should be used as values. Place this class in a package that can be imported into any Java program. Use your new class in an application that allows the user to select a color and draw a shape in that color.

19.16Write a program that determines and prints the number of duplicate words in a sentence. Treat uppercase and lowercase letters the same. Ignore punctuation.

19.17Rewrite your solution to Exercise 17.8 to use a LinkedList collection.

19.18Rewrite your solution to Exercise 17.9 to use a LinkedList collection.

19.19Write a program that takes a whole number input from a user and determines whether it is prime. If the number is not prime, display the unique prime factors of the number. Remember that a prime number's factors are only 1 and the prime number itself. Every number that is not prime has a unique prime factorization. For example, consider the number 54. The prime factors of 54 are 2, 3, 3 and 3. When the values are multiplied together, the result is 54. For the number 54, the prime factors output should be 2 and 3. Use Sets as part of your solution.

19.20Write a program that uses a StringTokenizer to tokenize a line of text input by the user and places each token in a treeSet. Print the elements of the treeSet. [Note: This should cause the elements to be printed in ascending sorted order.]

19.21The output of Fig. 19.17 (PriorityQueueTest) shows that PriorityQueue orders

Double elements in ascending order. Rewrite Fig. 19.17 so that it orders Double elements in descending order (i.e., 9.8 should be the highest-priority element rather than 3.2).

[Page 958]

Chapter 20. Introduction to Java Applets

Observe due measure, for right timing is in all things the most important factor.

George Wilhelp Friedrich Hegel

Painting is only a bridge linking the painter's mind with that of the viewer.

Eugene Delacroix

The direction in which education starts a man will determine his future in life.

Plato

OBJECTIVES

In this chapter you will learn:

To differentiate between applets and applications.

To observe some of Java's exciting capabilities through the JDK's demonstration applets.

To write simple applets.

To write a simple HyperText Markup Language (HTML) document to load an applet into an applet container and execute the applet.

Five methods that are called automatically by an applet container during an applet's life cycle.

[Page 959]

Outline

20.1 Introduction

20.2 Sample Applets Provided with the JDK

20.3 Simple Java Applet: Drawing a String

20.3.1 Executing an Applet in the appletviewer

20.3.2 Executing an Applet in a Web Browser

20.4 Applet Life-Cycle Methods

20.5 Initializing an Instance Variable with Method init

20.6 Sandbox Security Model

20.7 Internet and Web Resources

20.8 Wrap-Up

Summary

Terminology

Self-Review Exercises

Answers to Self-Review Exercises

Exercises

[Page 959 (continued)]

20.1. Introduction

[Note: This chapter and its exercises are intentionally small and simple for readers who wish to learn about applets after reading only the first few chapters of the bookpossibly just Chapters 2 and 3. We present more complex applets in Chapter 20, Multimedia: Applets and Applications, Chapter 23, Multithreading and Chapter 24, Networking.]

This chapter introduces appletsJava programs that can be embedded in HyperText Markup Language (HTML) documents (i.e., Web pages). When a browser loads a Web page containing an applet, the applet downloads into the Web browser and executes.

The browser that executes an applet is generically known as the applet container. The JDK includes the appletviewer applet container for testing applets as you develop them and before you embed them in Web pages. We typically demonstrate applets using the appletviewer. If you would like to execute your applets in a Web browser, be aware that some Web browsers do not support J2SE 5.0 by default. You can visit java.com and click the Get It Now button to install the J2SE Runtime Environment (JRE) 5.0 for your browser. Several popular browsers are supported.

[Page 959 (continued)]

20.2. Sample Applets Provided with the JDK

Let's consider several demonstration applets provided with the JDK. Each sample applet comes with its source code. Some programmers find it interesting to read this source code to learn new and exciting Java features.

The demonstration programs provided with the JDK are located in a directory called demo. For Windows, the default location of the JDK 5.0's demo directory is

C:\Program Files\Java\jdk1.5.0\demo

On UNIX/Linux/Mac OS X, the default location is the directory in which you install the JDK followed by jdk1.5.0/demofor example,

/usr/local/jdk1.5.0/demo

For other platforms, there will be a similar directory (or folder) structure. This chapter assumes that the JDK is installed in C:\Program Files\Java\jdk1.5.0\demo on Windows or in your home directory in ~/jdk1.5.0 on UNIX/Linux/Max OS X. You may need to update the locations specified here to reflect your chosen installation directory and disk drive, or a different version of the JDK.

[Page 960]

If you are using a Java development tool that does not come with the Sun Java demos, you can download the JDK (with the demos) from the Sun Microsystems Java Web site

java.sun.com/j2se/5.0/

TicTacToe Applet

The TicTacToe demonstration applet allows you to play Tic-Tac-Toe against the computer. To execute this applet, open a command window and change directories to the JDK's demo directory.

The demo directory contains several subdirectories. You can list them by issuing the dir command on Windows or the ls command on UNIX/Linux/Max OS X. We discuss sample programs in the applets and jfc directories. The applets directory contains several demonstration applets. The jfc (Java Foundation Classes) directory contains applets and applications that demonstrate Java's graphics and GUI features.

Change directories to the applets directory and list its contents to see the directory names for the demonstration applets. Figure 20.1 provides a brief description of each sample applet. If your browser supports J2SE 5.0, you can test these applets by opening the site java.sun.com/j2se/5.0/docs/relnotes/demos.html in your browser and clicking the link to each applet. We will demonstrate three of these applets by using the appletviewer command in a command window.

Figure 20.1. The examples from the applets directory.

 

[Page 961]

Example

Description

Animator

Performs one of four separate animations.

ArcTest

Demonstrates drawing arcs. You can interact with the applet to

 

change attributes of the arc that is displayed.