Subscribe: Learn Java
http://suckjava.blogspot.com/feeds/posts/default
Added By: otsongs Feedage Grade B rated
Language: English
Tags:
add  applet  collection  employee  interface  java  list  method  methods  new  object  public  set  thread thread  thread 
Rate this Feed
Rate this feedRate this feedRate this feedRate this feedRate this feed
Rate this feed 1 starRate this feed 2 starRate this feed 3 starRate this feed 4 starRate this feed 5 star

Comments (0)

Feed Details and Statistics Feed Statistics
Preview: Learn Java

Learn Java





Updated: 2014-10-02T22:11:03.540-07:00

 



Thread States

2009-06-07T04:39:53.697-07:00

A thread can be in one of the following states:

New thread. A thread is in this state after it has been created using the Thread constructor but before the start method has been invoked. A new thread will have no system resources allocated for it.

Runnable. A thread becomes runnable when the start method is invoked. This does not mean that a thread is actually running; in a single-processor computer system, another thread may be running at a given moment.

Not runnable. A thread cannot run. A thread becomes not runnable when the Thread class sleep or wait method has been invoked.

Dead. A thread dies when it stops. This occurs automatically when the thread's run method terminates.

Finally, the Thread class includes a method isAlive to test if a thread is alive. A thread is alive if it has been started and has not yet died. If a thread is alive, it is either runnable or not runnable. One cannot distinguish one state from the other. If a thread is not alive, it is either a new thread or dead. Again, it is not possible to distinguish between these states.



Synchronizing Threads

2009-06-07T04:37:52.903-07:00

A program may access the same object from separate concurrent threads. To ensure that only one thread at a time can access an object, we use the synchronized keyword. We can synchronize a method or block of code. When a thread executes a synchronized method or block of code, it places a lock on the associated object. This prevents any other thread from executing any synchronized method that accesses that object.

For example, the SynchronizedSumming class contains two synchronized methods,
add and subtract.

SynchronizedSumming

public class SynchronizedSumming
{
int result;

synchronized void add(int arg1)
{
result = result + arg1;
}

synchronized void subtract(int arg1)
{
result = result - arg1;
}
}


Any thread concurrently executing either of these methods is accessing the same shared SynchronizedSumming object. In particular, the SynchronizedSumming result variable is shared. So we do not want one thread to be executing the add method while another is concurrently executing the subtract method.

As soon as the first thread executes the add method, say, because it is synchronized, a lock is placed on the SynchronizedSumming object. This prevents another thread from executing any synchronized method that accesses the SynchronizedSumming object. In particular, a second thread cannot execute the subtract method. As soon as the first thread completes execution of the add method, the lock on the object is released.

Rather than place a lock on an object for the duration of an entire method, we may be able to isolate critical lines of code that access an object. For example, the add method may perform some time-consuming processing that does not affect the SynchronizedSumming object until the last statement.

We can create a synchronized block around this statement as follows:

void add(int arg1)
{

...
time consuming processing statements
...
synchronized (this)
{
result = result + arg1;
}
}


The this keyword ensures the current object, SynchronizedSumming, is locked. If the
synchronized block accesses another object, object_name, say, that we want to lock, we would use the statement

synchronized (object_name) {



Infinite Applet Thread Example

2009-06-07T04:36:38.268-07:00

If an applet executes a thread that is terminated only when the user closes or stops the applet, then we need to stop the thread in a different manner. This is best illustrated with an example: the ThreadForEver applet displays integers in turn starting at 1, incrementing the integer by 1, and only terminating when the user stops the applet.

ThreadForEver

import java.applet.*;
import java.awt.Graphics;
public class ThreadForEver extends Applet
implements Runnable {
Thread numbersThread;
int i = 1;
int xpos = 100;
int ypos = 50;
String text = '' ";

public void start()
{

numbersThread = new Thread(this);
numbersThread.start();

}

public void run()
{
while (numbersThread != null)
{
i++;
try
{
Thread.sleep(100);


}
catch (InterruptedException e) {}
text = Integer.toString(i);



repaint();
}
}

public void paint(Graphics g)
{
g.drawString(text, xpos, ypos);

}
public void stop()
{
numbersThread = null;
}
}


The applet implements a Runnable interface in the same manner as a finite applet thread. There is also no change to the applet start method. However, instead of a finite for loop in the run method, we specify the following while loop (line 18):

while (numbersThread != null) {

As long as the thread is not stopped, this condition will be satisfied. The run method delays execution for 100 milliseconds; this is not strictly required but is probably the minimum amount of time required to see individual integers appear on the screen. In lines 23–24, the string equivalents of the integers are displayed in the same position in the applet window using the repaint and paint methods as before.



Finite Applet Thread Example

2009-06-07T04:35:35.312-07:00

Before describing a threaded applet example, OneToTwenty is an applet that paints the numbers 1 to 20 in the applet window.

OneToTwenty

import java.applet.*;
import java.awt.Graphics;



public class OneToTwenty extends Applet
{

public void paint(Graphics g)
{
int i;
int xpos;
int ypos;

String text;
xpos = 0;
ypos = 50;



for (i=1; i<21; i++)
{
xpos = xpos + 20;
text = Integer.toString(i);
g.drawString(text, xpos, ypos);
}
}
}


This is a simple example of animation,

ThreadedNumbers

import java.applet.*;
import java.awt.Graphics;

public class ThreadedNumbers extends Applet implements Runnab le {
Thread numbersThread;
int xpos = 0;
int ypos = 0;
String text = '' ";

public void start()
{



}

public void run( ) {
int i;

xpos = 0;
ypos = 50;
for (i=1; i<21; i++)
{
try {
Thread.sleep(500);

} catch (InterruptedException e) {}
xpos = xpos + 20;
text = Integer.toString(i);
repaint();
}
}
public void paint(Graphics g)
{
g.drawString(text,xpos,ypos);
}
}

numbersThread = new Thread(this);
numbersThread.start();


Line 4 specifies in the applet class declaration that a Runnable interface is being implemented.

The start method (lines 10–13) overrides the applet class start method. In line 11, we pass an instance of the ThreadedNumbers class, this, as an argument to the Thread constructor. In line 12, the thread, numbersThread, is started.

Recall that starting a thread invokes the thread's run method. The run method (lines 15–28) includes a for loop that iterates over the numbers 1 to 20. For each iteration, we delay the thread's execution for half a second, 500 milliseconds, by means of the sleep method (line 22). In lines 24–25, we calculate the string equivalent, text, of the current iteration number and the horizontal position, xpos, of the number.

In line 26, we force the redrawing of the applet window by invoking the repaint method, which in turn, invokes the paint method. The thread is implicitly stopped as soon as the run method terminates.



The Runnable Interface

2009-06-07T04:33:46.362-07:00

An applet is created by extending the Applet or JApplet class; a class cannot be a subclass of more than one parent class, so we cannot extend the Thread class if we want to create a thread within an applet. To get around this, Java provides the Runnable interface. The interface is specified in the applet class declaration using the implements keyword, for example,

public class ThreadedNumbers extends Applet implements Runnable {

The Runnable interface consists of just one method, run, which takes no arguments. We create the run method within our applet subclass; the method contains the execution code for the thread similar to the run method for applications . We avoid having to subclass Thread by passing an instance of the applet subclass, this, to the newly created Thread object.

For example,

numbersThread = new Thread(this);

The thread is then started as follows:

numbersThread.start();



Thread Priorities

2009-06-07T04:32:29.025-07:00

By default, a thread inherits its priority from the program or thread that created it. It is possible to set a thread's priority using the Thread.setPriority method. A runnable thread with the highest priority is chosen first for execution. The setPriority method takes a value between Thread.MIN_PRIORITY and Thread.MAX_PRIORITY as an argument.

For example, in RunThreads, if we were to add the following statements prior to starting the threads:

thread1.setPriority(Thread.MIN_PRIORITY);
thread2.setPriority(Thread.MAX_PRIORITY);

the result would be to output the thread2 stream first. The two threads would still be interleaved because the result of using the sleep method on the higher priority thread2 is
to allow execution of the lower priority thread1.

Note that the Java thread priority scheduler does not usurp any timeslicing performed on a single-processor computer system using an operating system such as Windows NT. For example, if we were to remove the sleep method (line 14) from the run method of PrintNumbersThread but set the thread priorities as described earlier, we would output
all of thread2 followed by all of thread1. On a single-processor timeslicing system, such as Windows NT, the timeslice would be large enough to output the threads in their entirety.
However, if our program were modified so that each thread output many thousands of lines, not just ten, then the timeslicing would come into play switching between threads after several thousand iterations of each thread.



Multithreaded Application Example

2009-06-07T04:31:34.736-07:00

In Java application, PrintNumbersThread, which includes thread code that simply lists the numbers 1 to 10. The application will have two thread instances; the thread will append the thread instance name to the output number so that we can distinguish between the instances. Finally, we will use the sleep method within the thread's run method to cease execution every half- second so that we can interleave the two thread instances' output.

PrintNumbersThread

public class PrintNumbersThread extends Thread
{
String name;

public PrintNumbersThread(String threadName)
{
name = threadName;
}

public void run()
{
int i;

for (i=1; i<11; i++)
{
System.out.println(name + '': " + i);
try
{
Thread.sleep(500);
}
Catch(InterruptedException e){}

}
}
}


Line 1 indicates that PrintNumbersThread is a Thread subclass. The PrintNumbersThread class contains a constructor (lines 4–6) that simply assigns the supplied thread's instance name to the variable name. The run method (lines 8–17) contains a for loop that is executed ten times. Within the for loop (line 12), we print the thread instance's name followed by the numbers 1 to 10. In line 14, we use the sleep method to cease the current thread's execution for 500 milliseconds. This will enable any other started threads to resume execution. To use the sleep method, we must enclose the sleep statement within a try catch statement that handles an InterruptedException. Failure to do so will cause the program's compilation to fail.

The RunThreads application invokes PrintNumbersThread.


RunThreads

public class RunThreads
{

public static void main(String args[])
{
PrintNumbersThread thread1;
PrintNumbersThread thread2;
thread1 = new PrintNumbersThread(“Thread1”);

thread2 = new PrintNumbersThread(“Thread2”);

thread1.start();
thread2.start();
}
}



In lines 7–8, we create two instances of the thread, thread1 and thread2, by invoking the PrintNumbersThread constructor. In lines 9–10, we use the
java.lang.Thread.start method to start the two thread instances.

The output of RunThreads is as follows:

> java RunThreads
Thread1: 1
Thread2: 1
Thread1: 2
Thread2: 2
Thread1: 3
Thread2: 3
Thread1: 4
Thread2: 4
Thread1: 5
Thread2: 5
Thread1: 6
Thread2: 6
Thread1: 7
Thread2: 7
Thread1: 8

Thread2: 8
Thread1: 9
Thread2: 9
Thread1: 10
Thread2: 10



The Java Thread Class

2009-06-07T04:27:24.851-07:00

Java provides the java.lang.Thread class for explicitly creating and controlling threads. To use threads, first create a subclass of Thread. This subclass must include a run method; the code within the run method performs the thread's task. Each instantiation of this subclass corresponds to a single thread. To start the thread, the controlling program invokes the java.lang.Thread.start method. Invoking start causes the thread's run method to be invoked. This is done right away; we do not wait for another thread to complete the run method. In this way, multithreaded execution is achieved. The thread is implicitly stopped as soon as the run method terminates. One important method in the Thread class is sleep: this causes the thread to cease execution for a specified number of milliseconds.



Java Threads

2009-06-07T04:26:55.015-07:00

It is possible in Java for an individual program to simultaneously perform more than one task, or thread. All the programs discussed in this book so far implicitly use just one thread. Such a program is described as single threaded. Threads cannot exist independently; they always exist within the context of a program. A Java program can have any number of associated threads that are created explicitly; if a program has more than one associated thread, it is said to be multithreaded. Threads are sometimes described as execution contexts.

It is possible to delay execution of a thread: this feature of threads is typically used in animation. Multithreading is often used in applets that perform a number of independent tasks, one or more of which performs some lengthy initialization. With multithreading, the applet can perform some tasks while the lengthy tasks continue in the background. Typically, these lengthy tasks include loading images or accessing large volumes of data. A common use of multithreading is in client–server applications where the server may use one thread for each client.



The Collections Class

2009-06-07T04:25:40.678-07:00

The java.util.Collections class provides a number of methods that operate on collections (in most cases, lists). We will describe two such methods, sort and reverse,
in this section. The sort method sorts a list into the natural ascending order of its elements. Suppose we have created the following list:

List c = new ArrayList(); c.add("Smith");
c.add(''Jones");
c.add("Smith");
c.add("Brown");
c.add("Able");


then the statement

Collections.sort(c);

will sort the List c as follows:

Able Brown Jones Smith Smith

Like SortedSets, the sort method uses the String class implementation of the Comparable interface compareTo method to sort the Strings in lexicographic order. Similarly, if the collection contains Dates, then the Date class implementation of the Comparable interface compareTo method is used to sort the Dates in chronological order.

The reverse method reverses the order of elements in a list. For example, the statement

Collections.reverse(c);

will reverse the List c as follows:

Able Brown Smith Jones Smith



SortedMap Interface

2009-06-07T04:24:13.496-07:00

If we wish to maintain a map in ascending key order, we need to use the TreeMap implementation of the Map interface.

MapExample

import java.util.*;


public class MapExample
{

public static void main(String[] args)
{
Map m = new TreeMap();
m.put(new Integer(1),”Smith”);
m.put(new Integer(2),”Jones”);
m.put(new Integer(3),”Smith”);
m.put(new Integer(4),”Brown”);
m.put(new Integer(5),”Able”);


Collection c = m.keySet();
Iterator i = c.iterator();
while (i.hasNext() )
{
System.out.print( m.get(i.next()) + " ");
}
}
}


No other changes need to be made. The program output will now be

Smith Jones Smith Brown Able

The SortedMap interface inherits all the methods of the Map interface. In addition, SortedMap provides a number of methods, such as firstKey and lastKey, which make sense only for a map that is sorted. There is only one implementation of SortedMap, namely, TreeMap. To use the noninherited methods, we need to replace line 6 with

SortedMap m = new TreeMap();

The statements

System.out.println(''first key: " + m.firstKey());
System.out.println("last key: " + m.lastKey());


will produce the output

first key: 1
last key: 5




Map Interface

2009-06-07T04:22:21.631-07:00

A map is a grouping of keys and their corresponding values. A map cannot contain duplicate keys, and each key can have at most one associated value. Recall that a map is a top-level interface, so it does not inherit any of the Collection methods but is provided with its own methods similar in functionality to Collection methods. We will discuss three of the classes in the java.util package that implement the Map interface: HashMap, TreeMap, and Hashtable. HashMap is fastest but does not guarantee ordering; if ordering is required, TreeMap should be used. Prior to Java version 1.2, Hashtable was a separate data structure, since version 1.2, Hashtable is an implementation of the Map interface. The Hashtable class is similar to a HashMap, but a Hashtable is synchronized.
MapExample adds a number of elements to a HashMap, then prints the values of the map.

MapExample

import java.util.*;


public class MapExample
{

public static void main(String[] args)
{
Map m = new HashMap();
m.put(new Integer(1),”Smith”);
m.put(new Integer(2),”Jones”);
m.put(new Integer(3),”Smith”);
m.put(new Integer(4),”Brown”);
m.put(new Integer(5),”Able”);


Collection c = m.keySet();
Iterator i = c.iterator();
while (i.hasNext() )
{
System.out.print( m.get(i.next()) + " ");
}
}
}



The output of the program is

> java MapExample
Able Brown Smith Jones Smith


Note (line 6) that we have defined our HashMap as a Map type, m. We could have defined the HashMap as a HashMap type, as follows:

HashMap m = new HashMap();

However, as with a Collection, a Map type makes the code more generic: the code that follows the preceding statement will work whatever the implementation. To use a Hashtable implementation, we simply change the statement to

Map m = new Hashtable();

for the program to work.

In lines 7–11, we use the put(key, value) method to add pairs of keys with associated values to our map. Because the put arguments must be Object types, we use the Integer wrapper to convert integer numbers to objects.

There is no iterator object that iterates directly over a map. We need to use a collection or set view method that converts a map to a collection or set. We then iterate over this collection or set as before. The statement (line 13)

Collection c = m.keySet();

uses the collection view method keySet to return a collection, c, of keys contained in the map, m.

In lines 15–17, we then iterate over the collection c. In line 16, we use the Iterator.next method to obtain the next key in the collection. We look up the key's value using the Map.get method and print this value. Note that although in this case the map has been ordered by descending key order, the HashMap class does not guarantee ordering. If order has to be guaranteed, we must use the SortedMap interface.

Apart from keySet, the other set view methods are values, which returns a collection of values contained in the map, and entrySet, which returns a collection of key value mappings contained in the map. In the preceding MapExample, the entrySet view would be

5=Able 4=Brown 3=Smith 2=Jones 1=Smith



List Interface

2009-06-07T04:20:14.601-07:00

A list is an ordered collection that may include duplicate elements. The user has control over positional placing of elements in a list. The List interface, as well as inheriting allthe Collection methods, includes additional methods that manipulate the position of elements in a list. Three classes in the java.util package implement the List interface: ArrayList, LinkedList, and Vector. ArrayList, in general, is the fastest implementation; if, however, elements are frequently added to the beginning or end of a list or there are frequent deletions from a list, then the LinkedList implementation should be used. Prior to Java version 1.2, Vector was a separate data structure, since version 1.2 Vector is an implementation of the List interface. The Vector class is similar to anArrayList; however, Vector is synchronized while ArrayList is unsynchronized. All Collection framework implementations, apart from Vector and Hashtable, are unsynchronized.Consider CollectExample instead of adding elements to a set, we will add them to a list using the ArrayList implementation. CollectExample import java.util.*; public class CollectExample { public static void main(String[] args) { Collection c = new ArrayList(); c.add(''Smith"); c.add("Jones"); c.add("Smith"); c.add(''Brown"); c.add("Able"); Iterator i = c.iterator(); while (i.hasNext() ) { System.out.print(i.next() + " "); } } }The program will now output: java CollectExampleSmith Jones Smith Brown AbleNote that since we have a list, the duplicate elements ''Smith" are permitted. This example illustrates the polymorphic behavior of Collections. Our Collection interface methods work regardless of whether the implementation is a Set or List.If we want to use the LinkedList or Vector implementations in the program we only need to change the one statement. Both ArrayList and Vector have a default initial capacity of ten elements. This is automatically incremented when the list becomes full. We can change these default tuning parameters with the constructors ArrayList(int capacity) and Vector(int capacity). There are no tuning parameters for the LinkedList constructor.There are a number of methods in the List interface such as set, get, and subList that are not inherited from the Collection interface. To use any of these methods, we replacethe Collection type in line 6 with a List type, as follows:List c = new ArrayList();The set method is used to replace an element in a specified position in a list with a new element. For example, the statementc.set(3, "BROWN");replaces the fourth element (count from zero) "Brown" with "BROWN".The get method returns the element at the specified position. For example,Object o = c.get(3);returns the fourth element of c.The subList(startposition, endposition) method is used to create a sublist from the current list starting at startposition inclusive to endposition exclusive. For example, the statementList c1 = c.subList(2, 4);creates a sublist c1 with contents ''Smith", "Brown".The List interface also provides its own iterator, ListIterator, in addition to the Collection interface iterator. ListIterator inherits all the methods of Iterator but in addition provides methods such as previous and hasPrevious for iterating through a list in the reverse direction. previous returns the previous element in the list. hasPrevious returns true if there are more elements in the list when iterating in the reverse direction.The statementListIterator l = c.listIterator(5);creates a ListIterator, l, starting at the fourth (last) element in the list c. The argument, 5, is the element that would be r[...]



Implementing the Comparable Interfa

2009-06-07T04:16:40.539-07:00

Suppose we have an Employee class, with attributes employee number, name, and salary. We then create some Employee objects, and then add these to a SortedSet Collection.To keep these in a sorted order, we must implement the Comparable interface compareTo method. This method will define the sort order. The listing shows how we might do this for the Employee class.Employee class Employee implements Comparable { int empNumber; String name; int salary; public Employee(int empNumber, String name, int salary) { this.empNumber = empNumber; this.name = name; this.salary = salary; } public boolean equals(Object o) { if (o == this) { return true; } if (o == null) { return false; } if (getClass() != o.getClass() ) { return false; } Employee e = (Employee) o; return empNumber == e.empNumber && name.equals(e.name) && salary == e.salary; } public int hashCode() { int result = 17;result = 37 * result + empNumber;result = 37 * result + name.hashCode();result = 37 * result + salary return result; } public int compareTo (Object o) { Employee e = (Employee) o; return salary - e.salary; } } In line 1, the Employee class definition indicates that the Comparable interface is being implemented. Lines 6–10 define the Employee constructor. In lines 12–26, we override the equals method, as discussed in Section 5.2.1. In this case, two employee objects are equal if the contents of their empNumber, name, and salary fields are all equal. In lines 28–35, we override the hashCode method, as discussed in Section 5.2.2. If we do not override hashCode, a collection of Employee objects will not behave correctly. In lines37–40, we define the compareTo method.The Java Language Specification states the properties that an overridden compareTo method should exhibit. The main requirement is that the expression x.compareTo(y) will return a negative integer, zero, or a positive integer if the object x is less than, equal to, or greater than the object y. In our case, we want to sort according to salary order; sincesalary is a positive int, the expression salary - e.salary in line 39 satisfies the compareTo requirement.CreateEmployee creates five employee objects, adds them to a TreeSet collection, and then prints the set.CreateEmployee creates five employee objects, adds them to a TreeSet collection, and then prints the set.CreateEmployee import java.util.*; class CreateEmployee { public static void main(String[] args) {Employee emp1 = new Employee(1,”jones”,15000);Employee emp2 = new Employee(2,”sim”,20000);Employee emp3 = new Employee(3,”jones”,19000);Employee emp4 = new Employee(4,”thorpe”,18000);Employee emp5 = new Employee(5,”jones”,19000);Collection c = new TreeSet(); c.add(emp1); c.add(emp2); c.add(emp3); c.add(emp4); c.add(emp5); Iterator i = c.iterator(); while (i.hasNext() ) { Employee e = (Employee) i.next(); System.out.println(e.empNumber + '' " + e.name + " " + e.salary); } } } Note emp1 and emp3 are two different employees with the same surname JONES. Note that emp5 is a duplicate entry for employee number 3. The output, in salary order, is as follows:> java CreateEmployee1 JONES 150004 THORPE 180003 JONES 190002 SIM 20000Note that, being a set, the collection does not include the duplicate emp5.Suppose we want to sort by name and salary so that employees with the same name are ordered by salary. The code shows a new version of the Employee class compareTo method.compareTo public int compareTo(Object o) { Employee e = (Employee) o; int cmp = name.compareTo(e.name); return (cmp != 0 ? cmp: salary - e.salary) ; } In line 2, we cast the argument o to an Employee type. In line 3, we[...]



SortedSet Interface

2009-06-07T04:14:42.701-07:00

If we wish to maintain a set in ascending order, we need to use the TreeSet implementation of the SortedSet interface.

CollectExample

import java.util.*;

public class CollectExample
{

public static void main(String[] args)
{
Collection c = new TreeSet();;
c.add(''Smith");
c.add("Jones");
c.add("Smith");

c.add(''Brown");
c.add("Able");
Iterator i = c.iterator();
while (i.hasNext() ) {
System.out.print(i.next() + " ");
}
}
}



No other changes need to be made. The program output will now be

> java CollectExample
Able Brown Jones Smith


The order of this SortedSet is a consequence of the String class implementing the Comparable interface. There is only one method in Comparable, namely, compareTo. The compareTo method determines the ordering; in the case of the String implementation of compareTo, this is in lexicographic order. The Java Integer class (the object wrapper for int) and Date class, for example, also implement the Comparable interface. The Integer class compareTo method sorts the set in signed numerical order. The Date class compareTo method sorts the set in chronological order.

The SortedSet interface inherits all the methods of the Set interface. In addition, SortedSet provides a number of methods, such as first and last, which make sense only for a set that is sorted. There is only one implementation of SortedSet, namely, TreeSet. To use the noninherited methods, we need to replace the statement

Collection c = new TreeSet();

with

SortedSet c = new TreeSet();

The statements

System.out.println("first: " + c.first());
System.out.println("last: " + c.last());


will produce the output

first: Able
last: Smith




Set Interface

2009-06-07T04:12:23.375-07:00

A Set is a collection that cannot contain duplicate elements. This is identical to the mathematical definition of a set. All the methods in the Set interface are inherited from the Collection interface. Two classes in the java.util package implement the Set interface: HashSet and TreeSet. HashSet is faster but does not guarantee ordering; if ordering is required, TreeSet should be used. TreeSet is a sorted set.

CollectExample adds an number of elements to a HashSet, then prints the set.

CollectExample

import java.util.*;

public class CollectExample
{

public static void main(String[] args)
{
Collection c = new HashSet();
c.add(''Smith");
c.add("Jones");
c.add("Smith");

c.add(''Brown");
c.add("Able");
Iterator i = c.iterator();
while (i.hasNext() ) {
System.out.print(i.next() + " ");
}
}
}


The output from CollectExample is

> java CollectExample
Jones Smith Brown Able


Note that since duplicates are not allowed in sets, the set contains only one element named ''Smith". Note (line 6) that we have defined our HashSet as a Collection type, c.
We could have defined the HashSet as a Set type, as follows:

Set c = new HashSet();

However, as we shall see, using a Collection type makes writing generic code easier. A HashSet has a backing hash table of default initial capacity of 16 buckets (in J2SE 1.4) and load factor of 0.75. This means the hash table is allowed to become three quarters full before it is increased. We can change these default tuning parameters by the constructors HashSet(int capacity) and HashSet(int capacity, float load_factor).

Elements are added to the set using the add method. The Iterator object, which is part of the Collection interface, is used for traversing over collections. The Iterator has three associated methods.

hasNext() returns true if the iteration has more elements
next() returns the next element in the iteration
remove() removes the current element in the iteration from the collection


The program uses the hasNext and next methods to print the entire collection. The following code fragment is used to remove "Brown" from the collection using the Iterator remove method. Note that the Iterator next method returns an Object type.

Iterator i = c.iterator();
while (i.hasNext() )
{
Object o = i.next();

if (o.equals("Brown") )
{
i.remove();
}
}


We could remove "Brown" from the collection using the Collection remove method,as follows:

c.remove("Brown");

The Collection interface has a number of methods for performing bulk operations such as addAll and removeAll. For example, suppose we create a second collection c2, as follows:

Collection c2 = new HashSet();
c2.add("Thomas");

c2.add("Able");
The statement
c.addAll(c2);


adds the contents of c2 to c. This is equivalent to a mathematical set union. The resulting contents of c will be ''Smith", "Jones", "Brown", "Able", and "Thomas". The statement

c.removeAll(c2);

removes the contents of c2 from c, or put another way, the result is the set of elements in c that are not in c2. This is equivalent to a mathematical set difference. The resulting contents of c will be "Smith", "Jones", and "Brown".




Collections

2009-06-07T04:10:05.169-07:00

The Java Collections Framework consists of a number of interfaces and implementations for handling collections and maps. A collection groups multiple elements into a single unit.
A collection can be implemented as either of the classic data structures, lists or sets. A list allows duplicates, and maintains objects in the order in which they are added to the list. On the other hand, a set does not allow duplicates and provides either no particular ordering or an ordering based on the objects themselves regardless of the order in which they were added.

A map is a grouping of keys and their corresponding values. A map cannot contain duplicate keys, and each key can have at most one associated value. An example of a map
is a grouping of employee numbers (key) and the associated employee names (values).

The Collection Framework is a hierarchy of interfaces, as shown in Figure 1. This hierarchy is mirrored in the hierarchy of offered implementations, as shown in Figure 2. Collections provide examples of polymorphism: some operations are defined on all collections, and as collections get more specialized, operations that make sense only for that type are introduced into the hierarchy. We can write code that will manipulate a Collection type. This code will work regardless of the implementation of that Collection type.

(image)

The main top-level interfaces in the Collections Framework are Collection and Map. These interfaces define methods typically for adding elements to, removing elements from, and iterating through collections and maps. Sun does not provide a direct implementation of the Collection interface. Two more interfaces are inherited from the Collection
interface: the Set and List interfaces. The SortedSet interface, in turn, inherits from the Set interface. Sun provides classes that implement all these lower-level interfaces. The SortedMap interface inherits from the Map interface; implementations are provided for both the Map and SortedMap interfaces.



Applet Security

2009-06-07T04:06:50.467-07:00

Because an applet, resident on a Web server, is invoked by a browser on a client machine, most browsers place security restrictions on what an applet can do on a client machine. For example, applets cannot read, write, delete files, or list directories on the client machine. Applets cannot make network connections other than to the Web server it was loaded from. Applets cannot start new programs. Applets cannot read certain system properties such as the user's home directory or account name. The applet code cannot contain native methods, that is, methods written in a language other than Java.

Note that some browsers relax some of these restrictions when dealing with trusted, or signed, applets. An applet is held in a digitally signed jar (Java Archive) file. The technique of digitally signing a jar file is beyond the scope of this book. The recipient of this signed applet uses encryption techniques to verify the source of the applet. The applet
is then ''trusted" to perform most of the activities barred to untrusted applets.



Applet Life Cycle Methods

2009-06-07T04:06:18.517-07:00

Because applets are run from browsers, they differ from applications in that they do not have a main method. Instead, applets have an init method that is used to perform any applet initialization and is called only once in the lifetime of an applet.

The first method the Web browser invokes on loading the applet is the constructor. In MultiplyApplet, we could have overridden the MultiplyApplet constructor to perform some applet initialization. However, it is not always possible to perform all initialization within an applet constructor. For this reason, the applet class provides the init method, which is invoked after the applet object has been created.

The start method is invoked immediately after the init method. start, as the name suggests, starts the applet execution. start is also invoked if the user revisits the page containing the applet, having left it to visit other Web pages.

The stop method is used to stop the applet's execution, and is invoked when the user quits the browser or leaves the applet's page to visit other Web pages.

The destroy method is invoked after the stop method when the user quits the browser. The applet is unloaded, and any final cleanup actions, such as freeing up memory, are performed by this method.

Note that all these methods belong to the Applet class, and are inherited by the JApplet class, and so apply to both Swing and AWT applets.



Swing Applets

2009-06-07T04:05:52.590-07:00

The applet described in the previous section was a subclass of java.applet.Applet and as such did not use any Swing features. The advantage of this is that the applet can be invoked by any Java 1.0–enabled Web browser (virtually all browsers). The disadvantage is that we are restricted to the limited AWT graphical user interface. Applets can use the Swing features described earlier in this chapter. However, most browsers such as Microsoft Internet Explorer or Netscape Navigator that support only Java version 1.1 can run version 1.2 or Swing applets if they install a Java 1.2 plugin. However, if we use a plugin, we cannot use the >APPLET< tag in an HTML page. The tags that are used are more complex and differ from browser to browser; however, Sun does provide a utility for converting an >APPLET< tag to the plugin equivalent. The next listing shows the Swing version of the MultiplyApplet example.

(image)

Figure : Internet Explorer invoking Multiply Applet.

MultiplyApplet—Swing version

import javax.swing.*;
import java.awt.Container;

public class MultiplyApplet extends JApplet
{
private String param1;
private String param2;
private String resultString;
private int arg1;
private int arg2;
private int result;
Container cp;

public void init()
{

param1 = getParameter(''firstInt");
param2 = getParameter("secondInt");
arg1 = Integer.parseInt(param1);
arg2 = Integer.parseInt(param2);
result = arg1 * arg2;
cp = getContentPane();
Panel p = new Panel ();
cp.add(p);
}

class Panel extends JPanel
{

public void paintComponent (java.awt.Graphics g)
{
super.paintComponent(g);
resultString = Integer.toString(result);
g.drawString("The product of " + param1 + " and " + param2 + " is " + resultString, 50, 100);
}
}
}


There are only a couple of differences between the Swing and AWT versions. The first point to note is that our Multiply applet is a subclass of JApplet and not Applet. The JApplet class is actually a subclass of Applet and consequently inherits many of its methods. The second difference is that we do not draw the result directly on to the applet but create a JPanel subclass, Panel, and use the subclass paintComponent method to draw the result. This technique was described in Section 8.8. Panel is another example of an inner class. We could have declared Panel as a separate, outer, class. However, in that case, Panel would not have had access to MultiplyApplet's member variables, such as result, unless we declared these public. Note that we still use the AWT Graphics object in Swing. We can use the Multiply.html page to run this applet.



Applets

2009-06-07T03:59:55.905-07:00

In this section, we describe a simple applet, MultiplyApplet.java. This applet performs the same function , to output the product of two integers supplied as parameters. In contrast to an application that is a standalone program, an applet is invoked by a Web browser from a Web page. A Web page written in HTML (hypertext markup language) will contain an applet tag that specifies the location of the applet class files and the position of the applet on the Web page. The browser retrieves the applet class files across the Internet (of course, the applet class files may reside in the user's local computer), and runs the applet using the browser's JVM. Multiply.html is an example of a minimal Web page that loads MultiplyApplet.It is sufficient to note that an HTML page consists of a series of tags and content that describes how a Web page looks when displayed. Tags start with a character. Some tags have a slash after the leading appletviewer Multiply.htmlThe result is shown in Figure .Assuming we have a Java-enabled Web browser installed on our test computer, we simply need to enter the full HTML file path name in the browser's address area. For example, Figure 8.10 shows the output from a Microsoft Internet Explorer version 5 Web browser when the path name C:\JavaExamples\Multiply.html has been entered in the address area.[...]



Painting with Swing

2009-06-07T03:30:36.510-07:00

With Swing, we do not draw text or images directly onto a frame or applet. A component subclass is created, usually a subclass of JPanel, and the painting is performed in the subclasses' paintComponent method. An instance of this component subclass is then created and added to the content pane. The PaintPanel example shows a panel subclass performing painting.PaintPanelimport javax.swing.*;import java.awt.Dimension;import java.awt.Graphics;class PaintPanel extends JPanel{ public PaintPanel(){ setPreferredSize(new Dimension(110, 24)); } public void paintComponent (Graphics g){ super.paintComponent(g); g.drawString(''Text to be drawn" , 20, getHeight() ); } }The constructor, PaintPanel, uses the javax.swing.JPanel.setPreferredSize method to set the size of the panel, in this case, 110 pixels wide and 24 pixels high. The first statement in the paintComponent method must besuper.paintComponent(g);This causes the component to paint its background. The java.awt.Graphics.drawString method is used to paint the text. Two useful methods in javax.swing.JComponent that can be used with drawString are getHeight and getWidth. These return the current component height and width, respectively.An instance of PaintPanel is created and then added to the content pane, cp, as follows:PaintPanel p = new PaintPanel();cp.add(p);CustomerDetails import javax.swing.*; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.*; import java.awt.Color; import java.awt.Container;public class CustomerDetails extends JFrame implements ActionListener, ItemListener{ JTextArea addressArea; JScrollPane addressPane; JLabel addressLabel;Jlabel freqLabel;JComboBox freqButton;JCheckBox tradeButton;JRadioButton age1;JRadioButton age2;JRadioButton age3;JRadioButton age4;ButtonGroup ageButton;JPanel agePanel;JPanel freqPanel;Container cp;String[] comboString={''first time","occasionally", "frequently"}public CustomerDetails(){ /* set up layout panels */ cp = this.getContentPane(); cp.setLayout(new GridLayout(5,1)); agePanel = new JPanel(); agePanel.setLayout(new GridLayout(4,1) ); freqPanel = new JPanel(); freqPanel.setLayout(new GridLayout(1,2) ); /* set up name address label */ addressLabel = new JLabel("Enter Name and Address:"); cp.add(addressLabel) ; /* set up name address text area */addressArea = new JTextArea(3,12); addressPane = new JScrollPane(addressArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); cp.add(addressPane); /* set up Trade Customer Checkbox button */ tradeButton = new JCheckBox("Trade Customer", false); tradeButton.addItemListener(this); cp.add(tradeButton); /* set up shopping frequency combo box */ freqLabel = new JLabel( "How often do you shop with us: "); freqPanel.add(freqLabel); freqButton = new JComboBox(comboString); freqButton.addActionListener(this); freqPanel.add(freqButton); cp.add(freqPanel);/* set up age range radio button */ ageButton = new ButtonGroup();age1= new JRadioButton(''age under 20”);age2= new JRadioButton(“20-39”);age3= new JRadioButton(“40-59”);age4= new JRadioButton(“over 60”);ageButton.add(age1); ageButton.add(age2); ageButton.add(age3); ageButton.add(age4); age1.addActionListener(this); age2.addActionListener(this); age3.addActionListener(this);age4.addActionListener(this);agePanel.add(age1);agePanel.add(age2);agePanel.add(age3);agePanel.add(age4);this.addWindowListener(new WindowAdapter(){public void windowClosing(Windo[...]



Adapters in Event Handling

2009-06-07T03:28:16.419-07:00

All the listener interfaces we have described so far have just one associated method. Many other interfaces have several associated methods. We will use one such interface, WindowListener, as an example throughout this section. WindowListener has windowActivated, windowClosed, windowClosing, windowDeactivated, windowDeiconified, windowIconified, and windowOpened as associated methods. Recall from Section 5.4 that a class implementing an interface must have bodies for all the interface methods. This means that if we are interested in setting up only one listener interface method, windowClosing, say, we would need to write empty bodies for the other methods along the lines of

public void windowActivated((WindowEvent e))
{ }


To avoid this, we can use an adapter class: this implements empty bodies for all the interface methods. All event listener interfaces containing more than one method definition have a corresponding adapter class. In the case of WindowListener, this is WindowAdapter. The application class is defined as a subclass of the adapter class, and any nonempty interface methods are written within the application class.

If our application is a frame or applet subclass, then we cannot also define the application as a subclass of WindowAdapter. However, we can use inner classes. The following code fragment shows an inner class, MyWindowAdapter, that implements the windowClosing method. This, in turn, terminates the application when the user closes
the main window.

class MyWindowAdapter extends WindowAdapter
{
Publicvoid windowClosing(WindowEvent e)
{
System.exit(0);
}
}


The listener registration is performed by the statement

this.addWindowListener(new MyWindowAdapter() );

Note we do not register the application object to act as a listener, but an instance of the MyWindowAdapter class. The component for which we are registering a listener is the component involved when a user shuts the main window. This component is the current frame instance, identified by the keyword this.

If we create only a single object of the MyWindowAdapter class, we can dispense with giving the adapter subclass a name by using an anonymous inner class. We can replace the preceding MyWindowAdapter class and the addWindowListener statement with

this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});


This syntax reads as define an anonymous inner class as a subclass of WindowAdapter,create an instance of this inner class, and use this instance as an argument to the
addWindowListener method.



ListSelectionListener

2009-06-07T03:26:36.212-07:00

The ListSelectionListener interface is used to handle list selection events. These occur whenever the selection in a list or table has changed. Note that since the ListSelectionListener is a Swing and not an AWT listener interface, to abbreviate class names, the program should include the following statement:

import javax.swing.event.*;

The ListSelectionListener interface consists of a single method, valueChanged(ListSelection-Event e), where e is an object of type ListSelectionEvent. The method javax.swing.event. ListSelectionEvent.getSource obtains the source object generating the event. The value-Changed example uses the javax.swing.JList.getSelectedValue to determine the list item that has been selected.


valueChanged

public void valueChanged(ListSelectionEvent e)
{
if (e.getSource() instanceof JList)
{
if (shoppingList.getSelectedValue().equals(''ice axe"))
{
System.out.println("ice axe selected");
}
}
}



ItemListener

2009-06-07T03:25:47.461-07:00

ItemListeners are used to respond to item events. These are generated whenever an item's state changes. Typically, this occurs when an item is selected or deselected from a check box or a radio button. If, for example, a particular radio button is currently selected and another radio button is clicked, the item event is fired twice: once when the current radio button is deselected, and a second time when the new radio button is selected. The ItemListener interface consists of a single method, itemStateChanged. Specifically, this method has the signature

void itemStateChanged(ItemEvent e);

where e is an object of type ItemEvent. The java.awt.event.ItemEvent class contains a number of methods, including getSource. As with an action event, getSource returns the object that generated the event.

As an example, suppose we have registered an item listener for a check box, tradeButton. This could represent the Trade Customer check box in Figure 8.1. The itemStateChanged method is shown next.
itemStateChanged

public void itemStateChanged (ItemEvent e)
{
if (e.getSource() instanceof JCheckBox)
{
JCheckBox buttonLabel = (JCheckBox)
e.getItemSelectable();
if (buttonLabel == tradeButton)
{
if (e.getStateChange() == e.SELECTED) {
System.out.println(''Customer is trade");
}
else
{
System.out.println("Customer is not trade");
}
}
}
}

The statement (line 2)

if (e.getSource() instanceof JCheckBox) {

determines whether the event source is a check box. In that case, in lines 3–4, we use the java.awt.event.ItemEvent.getItemSelectable method to obtain the originator of the item event. This is then cast to a JCheckBox, buttonLabel. We can then use the ItemEvent.getState-Change method to determine whether tradeButton has been checked.