Presentation is loading. Please wait.

Presentation is loading. Please wait.

APPLETS.

Similar presentations


Presentation on theme: "APPLETS."— Presentation transcript:

1 APPLETS

2 What are the differences between Applets and Application?
What is Applets? An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a page. When you use a Java technology-enabled browser to view a page that contains an applet, the applet's code is transferred to your system and executed by the browser's Java Virtual Machine (JVM). What are the differences between Applets and Application? Applets do not use the main() method for initiating the execution of the code. Applets, when loaded, automatically call certain methods of Applet class to start and execute the applet code. Unlike stand – alone applications, applets cannot be run independently. They are run from inside a Web page using a special feature known as HTML tag. Applets cannot read from or write to the files in the local computer. Applets cannot communicate with other servers on the network. Applets cannot run any program from the local computer. Applets are restricted from using libraries from other languages such as C or C++. (Java language supports this feature through native methods.)

3 Applet Architecture An applet is a window – based program.
First, applets are event driven. Event – driven architecture impacts the design of an applet. An applet resembles a set of interrupt service routines. An applet waits until an event occurs. The AWT notifies the applet about an event by calling an event handler appropriate action and then quickly return control to the AWT. Second, the user initiates interaction with an applet - not the other way around. As you know, in a non - windowed program, when the program needs input, it will prompt the user and then call some input method, such as readLine(). This not the way it works in an applet. Instead, the user interacts with the applet as he or she wants, when must respond. For example, when the user clicks a mouse inside the applet’s window, a mouse – clicked event is generated. If the user presses a key while the applet’s window has input focus, a keypress event is generated. Applets can contain various controls, such as push buttons and check boxes.

4 Applet Architecture 12. When the user interacts with one of these controls, an event is generated. 13. While the architecture of an applet is not as easy to understand as that of a console – based program, Java’s AWT makes it as simple as possible. 14. If you have written programs for windows, you know how intimidating that environment can be. 15. Fortunately, Java’s AWT provides a much cleaner approach that is more quickly mastered.

5 An Applet Skeleton or Applet Life Cycle
Born Begin (Load Applet) Initialization start( ) Running stop( ) Idle Stopped start( ) Display paint( ) destroy( ) Dead End Destroyed Exit of Browser

6 An Applet Skeleton or Applet Life Cycle
All but the the most trivial applets override a set of methods that provides the basic mechanism by which the browser or applet viewer interfaces to the applet and controls its execution. Four of these methods – init( ), start( ), stop( ), and destroy( ) – are defined by Applet. Another, paint(), is defined by the AWT Component class. Default implementations for all of these methods are provided. Applets do no need to override those methods they do not use. However, only very simple applets will not need to define all of them. The applet states is: 1. Born or initialization state 2. Running state 3. Idle state 4. Dead or destroyed state 5. Display state

7 Initialization State Applet enters the initialisation state when it is first loaded. This is achieved by calling the init() method of Applet Class. The applet is born. At this stage, we may do the following, if required, a. Create objects needed by the applet. b. Set up initial values c. Load images or fonts d. set up colors public void init( ) { } Action

8 2. Running State Applets enters the running state when the system call the start () method of Applet Class. This occurs automatically after the applet is initailized. Starting can also occur if the applet is already in “stopped” state. For example, we may leave the web page containing the applet temporarily to another page and return back to the page. This again starts the applet running. Note that, unlike init() method, the start() method may be called more than once. We may override the start() method to create a threa to control the applet. public void start( ) { } Action

9 3. Idle or Stopped State An applet becomes idle when it is stopped from running. Stopping occurs automatically when we leave the page containing the currently running applet. We can also do so by calling the stop() method explicitly. If we use a thread to run the applet, then we must use stop() method to terminate the thread. We can achieve by overriding the stop( ) method: public void stop( ) { } Action

10 4. Dead State An applet is said to be dead when it is removed from memory. This occurs automatically by invoking the destroy( ) method when we quit the browser. Like initialization, destroying stage occurs only once in the applet’s life cycle. If the applet has created any resources. Like threads we may override the destroy( ) method to clean up these resouces. public void destroy( ) { } Action

11 5. Display State Applet moves to the display state whenever it has to perform some output operations on the screen. This happens immediately after the applet enters into the running state. The paint() method is called to accomplish this task. Almost every applet will have a paint() method. Like other methods in the life cycle, the default version of paint() method does absolutely nothing. We must therefore override this method if we want anything to be displayed on the screen. public void paint (Graphics g) { } Display Statements

12 Specified Colors Specified Colors Color.black 10. Color.pink
import java.awt.*; import java.applet.*; /* <applet code = "AppletDemo" width = 300 height = 300> </applet> */ public class AppletDemo extends Applet { String msg; public void init() setBackground(Color.cyan); } public void start() msg += "This is Start method"; public void stop() msg += "This is Stop method"; public void destroy() msg += "This is Destroy method"; public void paint(Graphics g) g.drawString(msg,100,100); Specified Colors Color.black Color.blue Color.cyan Color.darkGray Color.gray Color.green Color.lightGray Color.magenta Color.orange Specified Colors 10. Color.pink 11. Color.red 12. Color.white 13. Color.yellow

13 How the applets to be displayed in the Browser
<HTML> <HEAD> <TITLE>WELCOME TO cHETTINAD</TITLE> </HEAD> <BODY> <APPLET CODE = AppletDemo.class WIDTH = 300 HEIGHT = 200 </APPLET> </BODY> </HTML>

14 The HTML APPLET Tag < APPLET [CODEBASE = codebaseURL]
CODE = appletFile [ALT = alternateText] [NAME = appletInstanceName] WIDTH = pixels HEIGHT = pixels [ALIGN = alignment] [VSPACE = pixels] [HSPACE = pixels] > [<PARAM NAME = AttributeName VALUE = AttributeValue>] [HTML Displayed in the absence of Java] </APPLET>

15 ATTRIBUTE MEANING CODE = AppletFileName.class
Specifies the name of the applet class to be loaded. That is, the name of the already – compiled .class file in which the executable. Java bytecode for the applet is stored. This attribute must be specified. CODEBASE = codebase_URL (Optional) Specifies the URL of the directory in which the applet resides. If the applet resides in the same directory as the HTML file, then the CODEBASE attirbute may be omitted entirely. WIDTH = pixels HEIGHT = pixels These attributes specify the width and height of the space on the HTML page that will be reserved for the applet. NAME=applet_instance_name A name for the applet may optionally be specified so that other applets on the page may refer to this applet. This facilitates inter applet communication. ALIGN = alignment This optional attribute specifies where on the page the applet will appear. Possible values for alignment are TOP, BOTTOM, LEFT, RIGHT, MIDDLE, ABSMIDDLE, ABSBOTTOM, TEXTTOP, AND BASELINE. HSPACE = pixels Used only when ALIGN is set to LEFT or RIGHT , this attribute specifies the amount of horizontal blank space the browser should leave surrounding the applet. VSPACE = pixels Used only when some vertical alignment is specified with the ALIGN attribute (TOP, BOTTOM, etc.,) VSPACE specifes the amount of vertical blank space the browser should leave surrounding the applet. ALT = alternate_text Non – java browser will display this text where the applet would normally go. This attribute is optional. PARAM NAME AND VALUE The PARAM tag allows you to specify applet – specific arguments in an HTML page. Applets access their attributes with the getParameter() method

16 Passing Parameters to Applets
import java.awt.*; import java.applet.*; /* <applet code="ParamDemo" width = 300 height = 300> <param name = fontName value=Courier> <param name = fontSize value = 30> <param name = leading value=2> <param name = accountEnabled value = true> </applet> */ public class ParamDemo extends Applet { String fontName; int fontSize; float leading; boolean active; public void start() String param; fontName = getParameter("fontName"); if(fontName == null) fontName = "Not Found";

17 param = getParameter("fontSize");
try { if(param != null) //if not found fontSize = Integer.parseInt(param); else fontSize = 0; } catch(NumberFormatException e) fontSize = -1; param = getParameter("leading"); if(param != null) //if not found leading = Float.valueOf(param).floatValue(); leading = 0; leading = -1;

18 param = getParameter("accountEnabled");
if(param != null) active = Boolean.valueOf(param).booleanValue(); } public void paint(Graphics g) { g.drawString("Font name: " + fontName,0,10); g.drawString("Font Size: " + fontSize,0,20); g.drawString("Leading: " + leading, 0,42); g.drawString("Account Active: " + active,0,58);

19 getCodeBase() and getDocumentBase()
import java.awt.*; import java.applet.*; import java.net.*; /* <applet code=ParamDemo_2.class width = 300 height = 300> </applet> */ public class ParamDemo_2 extends Applet { public void paint(Graphics g) String msg; URL url = getCodeBase(); msg = "Code Base: " + url.toString(); g.drawString(msg,10,20); url = getDocumentBase(); msg = "Document Base: " + url.toString(); g.drawString(msg,10,40); }

20 The AudioClip Interface
The AudioClip interface defines these methods: 1. play ( ) – play a clip from the beginning. 2. stop ( ) – stop playing the clip. 3. loop ( ) – play the loop continuously. 4. getAudioClip ( ) - After you have loaded an audio clip import java.applet.*; import java.awt.event.*; import java.awt.*; /* <applet code=SoundExample width = 300 height = 300> </applet> */ public class SoundExample extends Applet implements MouseListener { AudioClip soundFile1; AudioClip soundFile2;

21 addMouseListener(this); setBackground(Color.yellow);
public void init() { soundFile1 = getAudioClip(getDocumentBase(),"c:\\windows\\media\\ding.wav"); soundFile2 = getAudioClip(getDocumentBase(),"c:\\windows\\media\\start.wav"); addMouseListener(this); setBackground(Color.yellow); soundFile1.play(); } public void paint(Graphics g) g.drawString("Click to hear a sound",20,20); public void mouseClicked(MouseEvent evt) soundFile2.play(); public void mousePressed(MouseEvent evt) {} public void mouseReleased(MouseEvent evt) {} public void mouseEntered(MouseEvent evt) {} public void mouseExited(MouseEvent evt) {}

22 AppletStub Interface The AppletStub interface provides a way to get information from the run-time browser environment. The Applet class provides methods with similar names that call these methods. Methods public abstract boolean isActive () The isActive() method returns the current state of the applet. While an applet is initializing, it is not active, and calls to isActive() return false. The system marks the applet active just prior to calling start(); after this point, calls to isActive() return true. public abstract URL getDocumentBase () The getDocumentBase() method returns the complete URL of the HTML file that loaded the applet. This method can be used with the getImage() or getAudioClip() methods to load an image or audio file relative to the HTML file. public abstract URL getCodeBase () The getCodeBase() method returns the complete URL of the .class file that contains the applet. This method can be used with the getImage() method or the getAudioClip() method to load an image or audio file relative to the .class file.

23 public abstract String getParameter (String name)
The getParameter() method allows you to get parameters from <PARAM> tags within the <APPLET> tag of the HTML file that loaded the applet. The name parameter of getParameter() must match the name string of the <PARAM> tag; name is case insensitive. The return value of getParameter() is the value associated with name; it is always a String regardless of the type of data in the tag. If name is not found within the <PARAM> tags of the <APPLET>, getParameter() returns null. public abstract void appletResize (int width, int height) The appletResize() method is called by the resize method of the Applet class. The method changes the size of the applet space to width x height. The browser must support changing the applet space; if it doesn't, the size remains unchanged.

24 The Delegation Event Model
1. The modern approach to handling events is based on the delegation event model, which defines standard and consistent mechanisms to generate and process events. 2. Its concept is quite simple: a source generates an event and sends it to one or more listeners. 3. In this scheme, the listener simply waits until it receives an event. 4. Once received, the listener processes the event and then returns. 5. The advantage of this design is that the application logic that processes events is cleanly separated from the user interface logic that generates those events. 6. A user interface element is able to “delegate” the processing of an event to a separate piece of code. Events In the delegation model, an event is an object that describes a state change in a source. It can be generated as a consequence of a person interacting with the elements in a graphical user interface. Some of the activities that cause events to be generated are pressing a button, entering a character via the keyboard, selecting an item in a list, and clicking the mouse. Event may also occur that are not directly caused by interactions with a user interface. For example, an event may be generated when a timer expires, a counter exceeds a value, a software or hardware failure occurs, or an operation is completed.

25 public void addTypeListener(TypeListener el)
Event Sources A source is an object that generates an event. This occurs when the internal state of that object changes in some way. Sources may generate more than one type of event. A source must register listeners in order for the listeners to receive notifications about a specific type of event. Each type of event has its own registration method. Here is the general form: public void addTypeListener(TypeListener el) 7. Here, type is the name of the event and el is a reference to the event listener. 8. For example the method that registers a keyboard event listener is called addKeyListener(). 9. The method that registers a mouse motion listener is called addMouseListener(). 10. When an event occurs, all registered listeners are notified and receive a copy of the event object. 11. This known as multicasting the event. Some sources may allow only one listener to register. 12. The general form of such method is this: public void addTypeListener(TypeListener el) throws java.util.TooManyListenersException

26 public void removeTypeListener(TypeListener el)
13. Here, Type is the name of the event and el is a reference to the event listener. 14.When such an event occurs, the registered listener is notified. This is known a s unicasting the event. 15. A source must also provide a method that allows a listener to unregister an interest in a specific type of event. 16. The general form of such a method is this: public void removeTypeListener(TypeListener el) 17. Here, Type is the name of the event and el is reference to the event listener. 18. For Example, to remove a keyboard listener, you would call removeKeyListener(). 19. The methods that add or remove listeners are privided by the source that generates events. 20. For example, the Component class provides methods to add and remove keyboard and mouse event listeners. Event Listeners 21. A Listener is an object that is notified when an event occurs. It has major requirements. 22. First, it must have been registered with one or more sources to receive notification about specific type of events. 23. Second, it must implement methods to receive and process these notifications.

27 24. The methods that receive and pricess events are defined in a set of interfaces found in java.awt.event. 25. For example, the MouseMotionListener interface defines two method to receive notifications when the mouse is dragged or moved. 26. Any object may receive and process one or both of these events if it provides an implementation of this interface.

28 EVENT CLASSES

29 EventObject(Object src)
Event Classes The classes that represent events are at the core of Java’s event handling mechanism. At the root of the Java event class hierarchy is EventObject, which is in java.util. It is the superclass for all events. Its one constructor is shown here: EventObject(Object src) 4. Here, src is the object that generates this event. 5. EventObject contains two methods: getSource() and toString(). 6. The getSource() method returns the source of the event. 7. Its general form is shown here: Object getSource() 8. As expected, toString() returns the string equivalent of the event. 9. The AWTEvent, defined within the java.awt package, is a subclass of EventObject. 10. It is the superclass of all AWT – based events used by the delegation event model. 11. Its getID() method can be used to determine the type of the event. The signature of this method is shown here: int getID()

30 EVENT CLASSES DESCRIPTION
The package java.awt.event defines several types of events that are generated by various user interface elements. EVENT CLASSES DESCRIPTION ActionEvent Generated when a button is pressed, a list item is double - clicked, or a menu item is selected. AdjustmentEvent Generated when a scroll bar is manupulated ComponentEvent Generated when a component is hidden, moved, resized, or becomes visible. ContainerEvent Generated when a component is added to or removed from a container. FocusEvent Generated when a component gains or loses keyboard focus. InputEvent Abstract super class for all component input event classes. ItemEvent Generated when a check box or list item is clicked; also occurs when a choice selection is made or a checkable menu item is selected or deselecte. KeyEvent Generated when input is received from the keyboard. MouseEvent Generated when the mouse is dragged, moved, clicked, pressed, or , released; also generated when the mouse enters or exits a component. MouseWheelEvent Generated when the mouse wheel is moved. TextEvent Generated when the value of a text area or text field is changed. WindowsEvent Generated when a window is activated, closed, deactivated, deiconified, iconified, opened, or quit.

31 The ActionEvent Class An ActionEvent is generated when a button is pressed, a list item is double - clicked, or a menu item is selected. The ActionEvent class defines fout integer constants that can be used to identify any modifiers associated with an action event: ALT_MASK, CTRL_MASK, META_MASK, and SHIFT_MASK. In addition. There is an integer constant, ACTION_PERFORMED, which can be used to identify action events. ActionEvent has these three constructors: ActionEvent(Object src, int type, String cmd) ActionEvent(Object src, int type, String cmd, int modifiers) ActionEvent(Object src, int type, String cmd, long when, int modifiers) 4. Here, src is a reference to the object that generated this event. 5. The type of the event is specified by type, and its command string is cmd. 6. The argument modifiers indicates which modifier key were pressed when the event was generated. 7. The when parameter specifies when the event occurred.

32 Action Event Example Button Click
import java.applet.*; import java.awt.*; import java.awt.event.*; /* <applet code="Button_Setnull.class" height=300 width=300> </applet> */ public class Button_Setnull extends Applet implements ActionListener { TextField tf1,tf2,tf3; Label l1,l2,l3; Button b1; int x,y,z; public void init() setBackground(Color.red); setForeground(Color.green); //setTitle("Addition of Two Numbers"); setLayout(null);

33 l1 = new Label("Enter the A Value");
l1.setBounds(0,0,100,25); l2 = new Label("Enter the B Value"); l2.setBounds(0,50,100,25); l3 = new Label("Addition of the Two Numbers"); l3.setBounds(0,100,170,25); tf1 = new TextField(10); tf1.setBounds(200,0,100,25); tf2 = new TextField(10); tf2.setBounds(200,50,100,25); tf3 = new TextField(10); tf3.setBounds(200,100,100,25); b1 = new Button("Click Addition"); b1.setBounds(100,150,150,25); add(l1); add(tf1); add(l2); add(tf2); add(l3); add(tf3); add(b1); b1.addActionListener(this); }

34 public void actionPerformed(ActionEvent ae)
{ if(ae.getActionCommand().equals("Click Addition")) x = Integer.parseInt(tf1.getText()); y = Integer.parseInt(tf2.getText()); z = x + y; tf3.setText(String.valueOf(z)); }

35 Action Event Example List Box item Double Click
import java.applet.*; import java.awt.*; import java.awt.event.*; /* <applet code=“Listbox_Setnull.class" height=300 width=1000> </applet> */ public class Listbox_Setnull extends Applet implements ActionListener { TextField tf1,tf2,tf3; Label l1,l2,l3; List ls; int x,y,z; public void init() setBackground(Color.red); setForeground(Color.green); setLayout(null); l1 = new Label("Enter the A Value"); l1.setBounds(0,0,100,25); l2 = new Label("Enter the B Value"); l2.setBounds(0,50,100,25); l3 = new Label("Compute the Two Numbers"); l3.setBounds(0,100,170,25);

36 tf1 = new TextField(10); tf1.setBounds(200,0,100,25); tf2 = new TextField(10); tf2.setBounds(200,50,100,25); tf3 = new TextField(10); tf3.setBounds(200,100,100,25); ls = new List(); ch.setBounds(100,150,150,25); ls.add(""); ls.add("Addition"); ls.add("Subtraction"); ls.add("Multiplication"); ls.add("Division"); ls.add("Clear"); ls.add("Total No. of Item"); ls.add("Get Selected Item"); add(l1); add(tf1); add(l2); add(tf2); add(l3); add(tf3); add(ls); ls.addActionListener(this); }

37 public void actionPerformed(ActionEvent ae)
{ if(ls.getSelectedIndex() == 1) x = Integer.parseInt(tf1.getText()); y = Integer.parseInt(tf2.getText()); z = x + y; tf3.setText(String.valueOf(z)); } if(ls.getSelectedIndex() == 2) z = x - y;

38 if(ls.getSelectedIndex() == 3)
{ x = Integer.parseInt(tf1.getText()); y = Integer.parseInt(tf2.getText()); z = x * y; tf3.setText(String.valueOf(z)); } if(ls.getSelectedIndex() == 4) z = x / y; tf3.setText(String.valueOf(z)); if(ls.getSelectedIndex() == 5) tf1.setText(""); tf2.setText(""); tf3.setText(""); if(ls.getSelectedIndex() == 6) int a = ch.getItemCount(); tf3.setText(String.valueOf(a)); if(ls.getSelectedIndex() == 7) tf3.setText(ch.getItem(ch.getSelectedIndex())); } }

39 The AdjustmentEvent Class
You can obtain the command name for the invoking ActionEvent object by using the getActionCommand() method, shown here: String getActionCommand() For example, when a button is pressed, and action event is generated that has a command name equal to the label on that button. The getModifiers() method returns a value that indicates which modifier keys(ALT,CTRL,META and SHIFT) were pressed when the event was generated. Its form is shown here: String getModifiers() The AdjustmentEvent Class An AdjustementEvent is generated by a scroll bar. There are five types of adjustment events. The AdjustementEvent class defines integer constants that can be used to identify them. BLOCK_DECREMENT – The user clicked inside the scroll bar to decrease its value. BLOCK_INCREMENT – The user Clicked inside the scroll bar to increase its value. TRACK – The slider was dragged. UNIT_DECREMENT – The button at the end of the scroll bar was clicked to decrease its value UNIT_INCREMENT – The button at the end of the scroll bar was clicked to increase its value.

40 Here is one AdjustmentEvent constructor:
In addition, there is an integer constant, ADJUSTMETN_VALUE_CHANGED, that indicates that a change has occurred. Here is one AdjustmentEvent constructor: AdjustmentEvent(Adjustable src, int id, int type, int data) Here, src is a reference to the object that generated this event. The id equals ADJUSTEMENT_VALUE_CHANGED. The type of the event is specified by type, and its associated data is data. The getAdjustable() method returns the object that generated the event. Its form is shown here: Adjustable getAdjustable() The type of the adjustement event may be obtained by the getAdjustmentType() method. It returns one of the constant defined by AdjustmentEvent. The general form is shown here: int getAdjustmentType() The amount of the adjustement can be obtained from the getValue() method, shown here int getValue()

41 AdjustmentEvent Example Horizontal and Vertical Scrollbar Changed
import java.applet.*; import java.awt.*; import java.awt.event.*; /* <applet code="Scroll_Setnull.class" height=300 width=1000> </applet> */ public class Scroll_Setnull extends Applet implements AdjustmentListener { TextField tf1,tf2,tf3; Label l1,l2,l3; Scrollbar sbh,sbv; int x,y,z; public void init() setBackground(Color.red); setForeground(Color.green); setLayout(null); l1 = new Label("Enter the A Value"); l1.setBounds(0,0,100,25); l2 = new Label("Enter the B Value"); l2.setBounds(0,50,100,25); l3 = new Label("Compute the Two Numbers"); l3.setBounds(0,100,170,25);

42 tf1 = new TextField(10); tf1.setBounds(200,0,100,25); tf2 = new TextField(10); tf2.setBounds(200,50,100,25); tf3 = new TextField(10); tf3.setBounds(200,100,100,25); int height = Integer.parseInt(getParameter("height")); int width = Integer.parseInt(getParameter("width")); sbh = new Scrollbar(Scrollbar.HORIZONTAL,0,1,0,height); sbh.setBounds(0,275,975,25); sbv = new Scrollbar(Scrollbar.VERTICAL,0,1,0,width); sbv.setBounds(975,0,25,300); sbh.setUnitIncrement(50); sbh.setBlockIncrement(50); sbv.setUnitIncrement(20); sbv.setBlockIncrement(20); add(l1); add(tf1); add(l2); add(tf2); add(l3); add(tf3); add(sbh); add(sbv); sbh.addAdjustmentListener(this); sbv.addAdjustmentListener(this); }

43 public void adjustmentValueChanged(AdjustmentEvent ae)
{ if(sbh.getValue() == 50) x = Integer.parseInt(tf1.getText()); y = Integer.parseInt(tf2.getText()); z = x + y; tf3.setText(String.valueOf(z)); } if(sbh.getValue() == 100) z = x - y;

44 if(sbh.getValue() == 150) { x = Integer.parseInt(tf1.getText()); y = Integer.parseInt(tf2.getText()); z = x * y; tf3.setText(String.valueOf(z)); } if(sbh.getValue() == 200) z = x / y; if(sbh.getValue() == 250) tf1.setText(""); tf2.setText(""); tf3.setText("");

45 The ComponentEvent Class
A ComponentEvent is generated when the size, position, or visibility of a component is changed. There are four types of component events. The ComponentEvent class defines integer constants that can be used to identify them. The constant and their meanings are shown here: COMPONENT_HIDDEN - The component was hidden COMPONENT_MOVED - The component was moved COMPONENT_RESIZED - The component was resized COMPONENT_SHOWN - The component became visible ComponentEvent has this constructor ComponentEvent(Component src, int type) Here, src is a reference to the object that generated this event. The type of the event is specified by type. ComponentEvent is the superclass either directly or indirectly of ContainerEvent, FocusEvent, KeyEvent, MouseEvent, and WindowEvent. The getComponent() method returns the component that generated the event. It is shown here: Component getComponent()

46 The ContainerEvent Class
A ContainerEvent is generated when a component is added to or removed from a container. There are two types of container events. The ContainerEvent class defines int constants that can be used to identify them: COMPONENT_ADDED and COMPONENET_REMOVED. They indicate that a component has been added or removed form the container. ContainerEvent is a subclass of ComponentEvent and has this constructor: ContainerEvent(Component src, int type, Component comp) Here, src is reference to the container that generated this event. The type of the event is specified by type, and the component that has been added to or removed from the container is comp. You can obtain a reference to the container that generated this event by using the getCotnainer() method, shown here: Container getContainer() The getChild() method returns a reference to the component that was added to or removed from the container. Its general form is shown here: Component getChild()

47 The FocusEvent Class A FocusEvent is generated when a component gains or loses input focus. These events are identified by the integer constants FOCUS_GAINED and FOCUS_LOST FocusEvent is a subclass of ComponentEvent and has threse constructor: FocusEvent(Component src, int type) FocusEvent(Component src, int type, boolean temporaryFlag) FocusEvent(Component src, int type, boolean temporaryFlag, Component other) Here, src is a reference to the component that generated this event. The type of the event is specified by type. The argument temporaryFlag is set to true if the focus event is temporary. Otherwise, it is set to false. The other component involved in the focus change, called the apposite component, is passed in other. Therefore, if a FOCUS_GAINED event occurred, other will refer to the component that lost focus. Conversely, if a FOCUS_LOST event occurred, other will refer to the component that gains focus.

48 FocusEvent Example Focus Gained and Focus Lost in TextBox
import java.applet.*; import java.awt.*; import java.awt.event.*; /* <applet code="Focus_Event.class" height=300 width=1000> </applet> */ public class Focus_Event extends Applet implements FocusListener { TextField tf1,tf2,tf3; public void init() setBackground(Color.red); setForeground(Color.green); tf1 = new TextField(10); tf1.setBounds(200,0,100,25); tf2 = new TextField(10); tf2.setBounds(200,50,100,25); tf3 = new TextField(10); tf3.setBounds(200,100,100,25); add(tf1); add(tf2); add(tf3); tf1.addFocusListener(this); tf2.addFocusListener(this); } FocusEvent Example Focus Gained and Focus Lost in TextBox

49 public void focusGained(FocusEvent fe)
{ tf2.setText("Focus Gained"); } public void focusLost(FocusEvent fe) tf1.setText("Focus Lost");

50 You can determine the other component by calling getOppositeComponent(), shown here.
Component getOppositeComponent() The isTemporary() method indicates if this focus change is temporary. Its form is shown here: boolean isTemprorary() The method returns true if the change is temporary. Otherwise, it returns false. The MouseEvent Class There are eight types of mouse events. The MouseEvent class defines the following integer constants that can be used to identify them: MOUSE_CLICKED - The user clicked the mouse. MOUSE_DRAGGED - The user dragged the mouse. MOUSE_ENTERED - The mouse entered a component. MOUSE_EXITED - The mouse exited from a component. MOUSE_MOVED - The mouse moved. MOUSE_PRESSED - The mouse was pressed. MOUSE_RELEASED - The mouse was released. MOUSE_WHEEL - The mouse wheel was moved.

51 Here, src is a reference to the component that generated the event.
MouseEvent is a subclass of InputEvent. Here is one of its constructor. MouseEvent(Component src, int type, long when, int modifiers, int x,int y, int clicks, boolean triggersPopup Here, src is a reference to the component that generated the event. The type of the event is specified by type. The system time at which the mouse event occurred is passed in when. The modifiers aregument indicates which modifiers were pressed when a mouse event occurred. The coordinates of the mouse are passed in x and y. The click count is passed in clicks. The triggersPopup flag indicates if this event causes a pop – up menu to appear on this platform Methods Description int getX() and int getY() These retrun the X and Y coordinates of the mouse when the event occured Point getPoint() It returns a Point object that contains the X, Y coordinates in its integer members. getClickCount() The methods obtains the number of mouse clicks for this event isPopupTrigger() This method tests if this event causes a pop – up menu to appear on this platform

52 MouseEvent Example in Mouse
import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="Mouse" width=500 height=500> </applet> */ public class Mouse extends Applet implements MouseListener,MouseMotionListener { int X=0,Y=20; String msg="MouseEvents"; public void init() addMouseListener(this); addMouseMotionListener(this); setBackground(Color.black); setForeground(Color.red); } public void mouseEntered(MouseEvent m) setBackground(Color.magenta); showStatus("Mouse Entered"); repaint(); public void mouseExited(MouseEvent m) showStatus("Mouse Exited"); MouseEvent Example in Mouse

53 public void mousePressed(MouseEvent m)
{ X=10; Y=20; msg="CCET"; setBackground(Color.green); repaint(); } public void mouseReleased(MouseEvent m) msg="Engineering"; setBackground(Color.blue); public void mouseMoved(MouseEvent m) X=m.getX(); Y=m.getY(); msg="College"; setBackground(Color.white); showStatus("Mouse Moved");

54 public void mouseDragged(MouseEvent m)
{ msg="CSE"; setBackground(Color.yellow); showStatus("Mouse Moved"+m.getX()+" "+m.getY()); repaint(); } public void mouseClicked(MouseEvent m) msg="Students"; setBackground(Color.pink); showStatus("Mouse Clicked"); public void paint(Graphics g) g.drawString(msg,X,Y);

55 The MouseWheelEvent Class
The MouseWheelEvent class encapsulates a mouse wheel event. If a mouse has a wheel, it is located between the left and right buttons. Mouse wheels, are used for scrolling. MouseWheelEvent defines these two integer constants. WHEEL_BLOCK_SCROLL - A page – up or page – down scroll event occurred WHEEL_UNIT_SCROLL - A line – up or line – down scroll event occured MouseWheelEvent defines the following constructor: MouseWheelEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks, boolean triggersPopup, int scrollHow, int amount, int count) Here, src is a reference to the object that generated the event. The type of the event is specified by type. The system time at which the mouse event occurred is passed in when. The modifiers argument indicates which modifiers were pressed when the event occurred. The coordinates of the mouse are passed in x and y. The number of clicks the wheel has rotated is passed in clicks. The triggers Popup flag indicates if this event causes a pop – up menu to appear on this platform. The scrollHow value must be either is passes in amount. The count parameter indicates the number of roational units that the wheel moved.

56 Methods Description int getWheelRotation() It returns the number of rotational units. If the value is positive, the wheel moved conterclockwise. If the value is negative, the wheel moved clockwise. int getScrollType() It returns either WHEEL_UNIT_SCORLL or WHEEL_BLOCK_SCROLL int getScrollAmount() If the scroll type is WHEEL_UNIT_SCROLL you can obtain the number of units to scroll by calling getScrollAmount(). The InputEvent Class The abstract class InputEvent is a subclass of ComponentEvent and is the superclass for component input events. Its subclasses are keyEvent and MouseEvent.InputEvent defines several integer constants that represent any modifiers, such as the control key being pressed, that might be assocated with the event. Originally, the InputEvent class defined the following eight values to represent the modifiers. ALT_MASK BUTTON2_MASK META_MASK BUTTON3_MASK SHIFT_MASK BUTTON1_MASK CTRL_MASK

57 7. The forms of these methods are shown here:
4. However, because of possible conflicts between the modifiers used by keyboard events and mouse events, and other issues, Java2 version 1.4, added the following extended modifier values. ALT_DOWN_MASK BUTTON2_DOWN_MASK META_DOWN_MASK BUTTON3_DOWN_MASK SHIFT_DOWN_MASK BUTTON1_DOWN_MASK CTRL_DOWN_MASK 5. When writing new code, it is recommended that you use the new, extended modifiers rather that the original modifiers. 6. To test if a modifier was pressed at the time an event is generated, use the isAltDown(), isAltGraphDown(), isControlDown(), isMetaDown(), and isShiftDown() methods. 7. The forms of these methods are shown here: boolean isAltDown() boolean isAltGraphDown() boolean isControlDown() boolean isMetaDown() boolean isShiftDown()

58 ItemEvent(ItemSelectable src, int type, Object entry, int state)
You can obtain a value that contains all of the original modifer flags by calling the getModifiers() method. It is shown here: int getModifiers() You can obtain the extended modifiers by called getModifiersEx(), which is shown here: int getModifiersEx() The ItemEvent Class An ItemEvent is generated when a check box or a list item is clicked or when a checkable menu item is selected or deselected. There are two types of item events, which are identified by the following integer constants. DESELECTED - The user deselected an item SELECTED - The user selected an item In addition, ItemEvent defines one integer constant, ITEM_STATE_CHANGED, that signifies a change of state. ItemEvent(ItemSelectable src, int type, Object entry, int state)

59 itemSelectable getItemSelectable()
3. Here, src is a reference to the component that generated this event. 4. For example, this might be a list or choice element. 5. The type of the event is specified by type. 6. The specific item that generated the item event is passed in entry. The current state of that item is in state. 7. The getItem() method can be used to obtain a reference to the item that generated an event. Its signature is shown here: Object getItem() 8. The getItemSelectable() method can be used to obtain a reference to the ItemSelectable object that generated an event. Its general form shown here: itemSelectable getItemSelectable() 9. Lists and choices are examples of user interface elements that implement the ItemSelectable interface. 10. The getStateChange() method returns the state change for the event. It is shown here: int getStateChange()

60 ItemEvent Example in Checkbox
import java.applet.*; import java.awt.*; import java.awt.event.*; /* <applet code="Checkbox_Setnull.class" height=300 width=1000> </applet> */ public class Checkbox_Setnull extends Applet implements ItemListener { TextField tf1,tf2,tf3; Label l1,l2,l3; Checkbox ch1,ch2,ch3,ch4,ch5; int x,y,z; public void init() setBackground(Color.red); setForeground(Color.green); setLayout(null); l1 = new Label("Enter the A Value"); l1.setBounds(0,0,100,25); l2 = new Label("Enter the B Value"); l2.setBounds(0,50,100,25); l3 = new Label("Addition of the Two Numbers"); l3.setBounds(0,100,170,25); ItemEvent Example in Checkbox

61 tf1 = new TextField(10); tf1.setBounds(200,0,100,25); tf2 = new TextField(10); tf2.setBounds(200,50,100,25); tf3 = new TextField(10); tf3.setBounds(200,100,100,25); ch1 = new Checkbox("Addition"); ch1.setBounds(100,150,150,25); ch2 = new Checkbox("Subtraction"); ch2.setBounds(250,150,150,25); ch3 = new Checkbox("Multiplication"); ch3.setBounds(400,150,150,25); ch4 = new Checkbox("Division"); ch4.setBounds(550,150,150,25); ch5 = new Checkbox("Clear"); ch5.setBounds(700,150,150,25); add(l1); add(tf1); add(l2); add(tf2); add(l3); add(tf3); add(ch1); add(ch2); add(ch3); add(ch4); add(ch5); ch1.addItemListener(this); ch2.addItemListener(this); ch3.addItemListener(this); ch4.addItemListener(this); ch5.addItemListener(this); }

62 public void itemStateChanged(ItemEvent ie)
{ if(ch1.getState()==true) x = Integer.parseInt(tf1.getText()); y = Integer.parseInt(tf2.getText()); z = x + y; tf3.setText(String.valueOf(z)); } if(ch2.getState()==true) z = x - y;

63 if(ch3.getState()==true)
{ x = Integer.parseInt(tf1.getText()); y = Integer.parseInt(tf2.getText()); z = x * y; tf3.setText(String.valueOf(z)); } if(ch4.getState()==true) z = x / y; if(ch5.getState()==true) tf1.setText(""); tf2.setText(""); tf3.setText("");

64 ItemEvent Example in CheckboxGroup
import java.applet.*; import java.awt.*; import java.awt.event.*; /* <applet code="Checkboxgroup_Setnull.class" height=300 width=1000> </applet> */ public class Checkboxgroup_Setnull extends Applet implements ItemListener { TextField tf1,tf2,tf3; Label l1,l2,l3; Checkbox ch1,ch2,ch3,ch4,ch5; CheckboxGroup cbg; int x,y,z; public void init() setBackground(Color.red); setForeground(Color.green); setLayout(null); cbg = new CheckboxGroup(); l1 = new Label("Enter the A Value"); l1.setBounds(0,0,100,25); l2 = new Label("Enter the B Value"); l2.setBounds(0,50,100,25); l3 = new Label("Compute the Two Numbers"); l3.setBounds(0,100,170,25); ItemEvent Example in CheckboxGroup

65 tf1 = new TextField(10); tf1.setBounds(200,0,100,25); tf2 = new TextField(10); tf2.setBounds(200,50,100,25); tf3 = new TextField(10); tf3.setBounds(200,100,100,25); ch1 = new Checkbox("Addition",cbg,false); ch1.setBounds(100,150,150,25); ch2 = new Checkbox("Subtraction",cbg,false); ch2.setBounds(250,150,150,25); ch3 = new Checkbox("Multiplication",cbg,false); ch3.setBounds(400,150,150,25); ch4 = new Checkbox("Division",cbg,false); ch4.setBounds(550,150,150,25); ch5 = new Checkbox("Clear",cbg,false); ch5.setBounds(700,150,150,25); add(l1); add(tf1); add(l2); add(tf2); add(l3); add(tf3); add(ch1); add(ch2); add(ch3); add(ch4); add(ch5); ch1.addItemListener(this); ch2.addItemListener(this); ch3.addItemListener(this); ch4.addItemListener(this); ch5.addItemListener(this); }

66 public void itemStateChanged(ItemEvent ie)
{ if(ch1.getState()==true) x = Integer.parseInt(tf1.getText()); y = Integer.parseInt(tf2.getText()); z = x + y; tf3.setText(String.valueOf(z)); l3.setVisible(true); tf3.setVisible(true); } if(ch2.getState()==true) z = x - y;

67 if(ch3.getState()==true)
{ x = Integer.parseInt(tf1.getText()); y = Integer.parseInt(tf2.getText()); z = x * y; tf3.setText(String.valueOf(z)); } if(ch4.getState()==true) z = x / y; if(ch5.getState()==true) tf1.setText(""); tf2.setText(""); tf3.setText("");

68 ItemEvent Example in Choice Box
import java.applet.*; import java.awt.*; import java.awt.event.*; /* <applet code="Choicebox_Setnull.class" height=300 width=1000> </applet> */ public class Choicebox_Setnull extends Applet implements ItemListener { TextField tf1,tf2,tf3; Label l1,l2,l3; Choice ch; int x,y,z; public void init() setBackground(Color.red); setForeground(Color.green); setLayout(null); l1 = new Label("Enter the A Value"); l1.setBounds(0,0,100,25); l2 = new Label("Enter the B Value"); l2.setBounds(0,50,100,25); l3 = new Label("Compute the Two Numbers"); l3.setBounds(0,100,170,25);

69 tf1 = new TextField(10); tf1.setBounds(200,0,100,25); tf2 = new TextField(10); tf2.setBounds(200,50,100,25); tf3 = new TextField(10); tf3.setBounds(200,100,100,25); ch = new Choice(); ch.setBounds(100,150,150,25); ch.add(""); ch.add("Addition"); ch.add("Subtraction"); ch.add("Multiplication"); ch.add("Division"); ch.add("Clear"); ch.add("Total No. of Item"); ch.add("Get Selected Item"); add(l1); add(tf1); add(l2); add(tf2); add(l3); add(tf3); add(ch); ch.addItemListener(this); }

70 public void itemStateChanged(ItemEvent ie)
{ if(ch.getSelectedIndex() == 1) x = Integer.parseInt(tf1.getText()); y = Integer.parseInt(tf2.getText()); z = x + y; tf3.setText(String.valueOf(z)); } if(ch.getSelectedIndex() == 2) z = x - y;

71 if(ch.getSelectedIndex() == 3)
{ x = Integer.parseInt(tf1.getText()); y = Integer.parseInt(tf2.getText()); z = x * y; tf3.setText(String.valueOf(z)); } if(ch.getSelectedIndex() == 4) z = x / y; tf3.setText(String.valueOf(z)); if(ch.getSelectedIndex() == 5) tf1.setText(""); tf2.setText(""); tf3.setText(""); if(ch.getSelectedIndex() == 6) int a = ch.getItemCount(); tf3.setText(String.valueOf(a)); if(ch.getSelectedIndex() == 7) tf3.setText(ch.getItem(ch.getSelectedIndex())); } }

72 The KeyEvent Class A KeyEvent is generated when keyboard input occurs.
There are three types of key events, which are identified by these integer constants: KEY_PRESSED, KEY_RELEASED and KEY_TYPED. The first two events are generated when any key is pressed or released. The last event occurs only when a character is generated. Remember, not all key presses result in characters. For example, pressing the SHIFT key does not generate a character. There are many other integer constants that are defined by KeyEvent. For example, VK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents of the numbers and letters. Here are some others: VK_ENTER VK_ESCAPE VK_CANCEL VK_UP VK_DOWN VK_LEFT VK_RIGHT VK_PAGE_DOWN VK_PAGE_UP VK_SHIFT VK_ALT VK_CONTROL

73 9. The VK constants specify virtual key codes and are independent of any modifiers, such as control, shift, or alt. KeyEvent is a subclass of InputEvent. 10. Here are two of its constructors: KeyEvent(Component src, int type, long when, int modifiers, int code) KeyEvent(Component src, int type, long when, int modifiers, int code, char ch) 11. Here, src is a reference to the component that generated the event. 12. The type of the event is specified by type. 13. The system time at which the key was pressed is passed in when. 14. The modifiers argument indicates which modifiers where pressed when this key event occurred. 15. The virutal key code, such as VK_UP, VK_A, and so forth, is passed in code. 16. The character equivalent is passed in ch. If no valid character exists, then ch contains CHAR_UNDEFINED. 17. For KEY_TYPED events, code will contain VK_UNDEFINED. 18. The KeyEvent class defines several methods, but the most commonly used ones are getKeyChar(), which returns the character that was entered, and getKeyCode(), which returns the key code.

74 KeyEvent Example in Keyboard
//the key event handles import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code=Key_Event.class width=300 height=100> </applet> */ public class Key_Event extends Applet implements KeyListener { String msg=""; int x=10,y=20; public void init() addKeyListener(this); } public void keyPressed(KeyEvent ke) showStatus("Key Down"); public void keyReleased(KeyEvent ke) showStatus("Key Up"); public void keyTyped(KeyEvent ke) msg+=ke.getKeyChar(); repaint(); public void paint(Graphics g) g.drawString(msg,x,y); KeyEvent Example in Keyboard

75 The TextEvent Class Their general forms are shown here:
char getKeyChar() int getKeyCode() If not valid character is available, then getKeyChar() returns CHAR_UNDEFINED. When a KEY_TYPED event occurs, getKeyCode() returns VK_UNDEFINED The TextEvent Class Instances of this class describe text events. These are generated by text fields and text areas when characters are entered by a user or program. TextEvent defines the integer constant TEXT_VALUE_CHANGED. The one constructor for this class is shown here: TextEvent(Object src, int type) Here, src is a reference to the object that generated this event. The type of the event is specified by type.

76 TextEvent Example in Textbox
import java.applet.*; import java.awt.*; import java.awt.event.*; /* <applet code="Text_Event.class" height=300 width=1000> </applet> */ public class Text_Event extends Applet implements TextListener { TextField tf1,tf2,tf3; public void init() setBackground(Color.red); setForeground(Color.green); tf1 = new TextField(10); tf1.setBounds(200,0,100,25); tf2 = new TextField(10); tf2.setBounds(200,50,100,25); tf3 = new TextField(10); tf3.setBounds(200,100,100,25); add(tf1); add(tf2); add(tf3); tf1.addTextListener(this); tf2.addTextListener(this); } public void textValueChanged(TextEvent te) tf3.setText(tf1.getText()); TextEvent Example in Textbox

77 The WindowEvent Class There are ten types of window events. The WindowEvent class defines integer constants that can be used to identify them. The constant and their meanings are shown here: WINDOW_ACTIVATED - The window was activate WINDOW_CLOSED - The window has been closed WINDOW_CLOSING - The user requested that the window be closed WINDOW_DEACTIVATED - The window was deactivated. WINDOW_DEICONIFIED - The window was deiconified. WINDOW_GAINED_FOCUS - The window gained input focus. WINDOW_ICONIFIED - The window was iconified. WINDOW_LOST_FOCUS - The window lost input focus. WINDOW_OPENED - The window was opened. WINDOW_STATE_CHANGED - The state of the window changed.

78 WindowEvent(Window src, int type)
WindowEvent is a subclass of ComponentEvent. It defines the following constructor. WindowEvent(Window src, int type) Here, src is a reference to the object that generated this event. The type of the event is type. The most commonly used method in this class is getWindow(). It returns the Window object that generated the event. Its general form is shown here: Window getWindow()

79 Event Listener Interfaces Event Listener Interfaces Methods
Event Classes Event Listener Interfaces Event Listener Interfaces Methods ActionEvent ActionListener void actionPerformed(ActionEvent ae) AdjustmentEvent AdjustmentListener void adjustmentValueChanged(AdjustmentEvent ae) ComponentEvent ComponentListener void componentResized(ComponentEvent ce) void componentMoved(ComponentEvent ce) void componentShown(ComponentEvent ce) void componentHidden(CommonentEvent ce) ContainerEvent ContainerListener void componentAdded(ContainerEvent ce) void componentRemoved(ContainterEvent ce) FocusEvent FocusListener void focusGained(FocusEvent fe) void focusLost(FocusEvent fe) InputEvent ItemEvent ItemListener void itemStateChanged(ItemEvent ie) KeyEvent KeyListener Void keyPressed(KeyEvent ke) Void keyReleased(KeyEvent ke) Void KeyTyped(KeyEvent ke) MouseEvent MouseListener MouseMotionListener void mouseClicked(MouseEvent me) void mouseEntered(MouseEvent me) void mouseExited(MouseEvent me) void mousePressed(MouseEvent me) void mouseReleased(MouseEvent me) void mouseDragged(MouseEvent me) void mouseMoved(MouseEvent me)

80 Event Listener Interfaces Event Listener Interfaces Methods
Event Classes Event Listener Interfaces Event Listener Interfaces Methods MouseWheelEvent MouseWheelListener void mouseWheelMoved(MouseWheelEvent mwe) TextEvent TextListener void textChanged(TextEvent te) WindowEvent WindowsListener WindowFocusListener void windowActivated(WindowEvent we) void windowClosed(WindowEvent we) void windowClosing(WindowEvent we) void windowDeactivated(WindowEvent we) void windowDeiconified(WindowEvent we) void windowIconified(WindowEvent we) void windowOpened(WindowEvent we) Void windowGainedFocus(WindowEvent we) Void windowLostFocus(WindowEvent we)

81 Sources of Events Event Source Description Button
Generates action events when the button is pressed. Checkbox Generates item event s when the check box is selected or deselected. Choice Generates item event s when the choice is changed. List Generates action event s when an item is double – clicked; generates item event when an item is selected or deselected. Menu Item Generates action event swhen a menu item is selected; generates item events when a checkable menu item is selected or deselected. Scrollbar Generates adjustment event when the scroll bar is manipulated. Text components Generates text events when the user enters a character. Window Generated window events when a window is activated, closed, deactivated, deiconified, iconified, opened, or quit.

82 The Collection Interface
The Collection interface is the foundation upon which the collections framework is built. It declares the core methods that all collections will have. Several of these methods can throw an UnsupportedOperationException. A ClassCastException is generated when one object is incompatible with another, such as when an attempt is made to add an incompatible object to a collection.

83

84 5. Objects are added to a collection by calling add( ).
6. Notice that add( ) takes an argument of type Object. 7. Because Object is a superclass of all classes, any type of object may be stored in a collection. 8. However, primitive types may not. 9. For example, a collection cannot directly store values of type int, char, double, and so forth. 10. You can add the entire contents of one collection to another by calling addAll( ). 11. You can remove an object by using remove( ). 12. To remove a group of objects, call removeAll( ). 13. You can remove all elements except those of a specified group by calling retainAll( ). 14. To empty a collection, call clear( ). 15. You can determine whether a collection contains a specific object by calling contains( ). 16. To determine whether one collection contains all the members of another, call containsAll( ). 17. You can determine when a collection is empty by calling isEmpty( ). 18. The number of elements currently held in a collection can be determined by calling size( ). 19. The toArray( ) method returns an array that contains the elements stored in the invoking collection. 20. This method is more important than it might at first seem. 21. Often, processing the contents of a collection by using array-like syntax is advantageous. 22. By providing a pathway between collections and arrays, you can have the best of both worlds. 23. Two collections can be compared for equality by calling equals( ). 24. The precise meaning of “equality” may differ from collection to collection. 25. For example, you can implement equals( ) so that it compares the values of elements stored in the collection. 26. Alternatively, equals( ) can compare references to those elements. 27. One more very important method is iterator( ), which returns an iterator to a collection.

85 The List Interface The List interface extends Collection and declares the behavior of a collection that stores a sequence of elements. Elements can be inserted or accessed by their position in the list, using a zero-based index. A list may contain duplicate elements. Note again that several of these methods will throw an UnsupportedOperationException if the collection cannot be modified, and a ClassCastException is generated when one object is incompatible with another, such as when an attempt is made to add an incompatible object to a collection. To the versions of add( ) and addAll( ) defined by Collection, List adds the methods add(int, Object) and addAll(int, Collection). These methods insert elements at the specified index. Also, the semantics of add(Object) and addAll(Collection) defined by Collection are changed by List so that they add elements to the end of the list. To obtain the object stored at a specific location, call get( ) with the index of the object. To assign a value to an element in the list, call set( ), specifying the index of the object to be changed. To find the index of an object, use indexOf( ) or lastIndexOf( ).

86

87 import java.util.*; public class DemoList { public static void main(String[] args) { List ls = new LinkedList(); for(int i=1; i<=5; i++){ ls.add(new StringBuffer("Object " + i)); } //display how many objects are in the collection System.out.println("The collection has " + ls.size() + "objects"); //Instantiate a ListIterator ListIterator li = ls.listIterator(); System.out.println("Forward Reading"); //Forward direction while(li.hasNext()){ System.out.println(" " + li.next()); System.out.println("Backward Reading"); //backword direction while(li.hasPrevious()) System.out.println(" " + li.previous());

88 The Set Interface The Set interface defines a set.
It extends Collection and declares the behavior of a collection that does not allow duplicate elements. Therefore, the add( ) method returns false if an attempt is made to add duplicate elements to a set. It does not define any additional methods of its own. public class SetDemo { public static void main(String[] args) // Set example with implement TreeSet Set s=new TreeSet(); s.add("b"); s.add("a"); s.add("d"); s.add("c"); Iterator it=s.iterator(); while(it.hasNext()) String value=(String)it.next(); System.out.println("Value :"+value); }

89 The SortedSet Interface
The SortedSet interface extends Set and declares the behavior of a set sorted in ascending order. In addition to those methods defined by Set, the SortedSet interface declares the methods. Several methods throw a NoSuchElementException when no items are contained in the invoking set. A ClassCastException is thrown when an object is incompatible with the elements in a set. A NullPointerException is thrown if an attempt is made to use a null object and null is not allowed in the set. SortedSet defines several methods that make set processing more convenient. To obtain the first object in the set, call first( ). To get the last element, use last( ). You can obtain a subset of a sorted set by calling subSet( ), specifying the first and last object in the set. If you need the subset that starts with the first element in the set, use headSet( ). If you want the subset that ends the set, use tailSet( ).

90

91 import java.util.Iterator;
import java.util.SortedSet; import java.util.TreeSet; public class SortedSetExample { public static void main(String[] args) { SortedSet<String> ss=new TreeSet<String>(); ss.add("a"); ss.add("e"); ss.add("g"); ss.add("b"); ss.add("c"); Iterator it=ss.iterator(); while(it.hasNext()) { String value=(String)it.next(); System.out.println("Value :"+value); }

92 COLLECTION CLASSES

93 Class Description AbstractCollection Implements most of the Collection interface. AbstractList Extends AbstractCollection and implements most of the List interface. AbstractSequentialList Extends AbstractList for use by a collection that uses sequential rather than random access of its elements. LinkedList Implements a linked list by extending AbstractSequentialList. ArrayList Implements a dynamic array by extending AbstractList. AbstractSet Extends AbstractCollection and implements most of the Set interface. HashSet Extends AbstractSet for use with a hash table. LinkedHashSet Extends HashSet to allow insertion-order iterations. TreeSet Implements a set stored in a tree. Extends AbstractSet.

94 The ArrayList class extends AbstractList and implements the List interface.
ArrayList supports dynamic arrays that can grow as needed. In Java, standard arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold. But, sometimes, you may not know until run time precisely how large of an array you need. To handle this situation, the collections framework defines ArrayList. In essence, an ArrayList is a variable-length array of object references. That is, an ArrayList can dynamically increase or decrease in size. Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk. ArrayList has the constructors shown here: ArrayList( ) ArrayList(Collection c) ArrayList(int capacity) The first constructor builds an empty array list. The second constructor builds an array list that is initialized with the elements of the collection c. The third constructor builds an array list that has the specified initial capacity. The capacity is the size of the underlying array that is used to store the elements. The capacity grows automatically as elements are added to an array list.

95 import java.util.*; class ArrayListDemo { public static void main(String args[]) // create an array list ArrayList al = new ArrayList(); System.out.println("Initial size of al: " + al.size()); // add elements to the array list al.add("C"); al.add("A"); al.add("E"); al.add("B"); al.add("D"); al.add("F"); al.add(1, "A2"); System.out.println("Size of al after additions: " + al.size()); // display the array list System.out.println("Contents of al: " + al); // Remove elements from the array list al.remove("F"); al.remove(2); System.out.println("Size of al after deletions: " + al.size()); }

96 The LinkedList Class The LinkedList class extends AbstractSequentialList and implements the List interface. It provides a linked-list data structure. It has the two constructors, shown here: LinkedList( ) LinkedList(Collection c) 3. The first constructor builds an empty linked list. 4. The second constructor builds a linked list that is initialized with the elements of the collection c. 5. In addition to the methods that it inherits, the LinkedList class defines some useful methods of its own for manipulating and accessing lists. 6. To add elements to the start of the list, use addFirst( ); to add elements to the end, use addLast( ). 7. Their signatures are shown here: void addFirst(Object obj) void addLast(Object obj) Here, obj is the item being added. To obtain the first element, call getFirst( ). To retrieve the last element, call getLast( ). Their signatures are shown here:

97 Object getFirst( ) Object getLast( )
To remove the first element, use removeFirst( ); to remove the last element, call removeLast( ). They are shown here: Object removeFirst( ) Object removeLast( ) import java.util.*; class LinkedListDemo { public static void main(String args[]) // create a linked list LinkedList ll = new LinkedList(); // add elements to the linked list ll.add("F"); ll.add("B"); ll.add("D"); ll.add("E"); ll.add("C"); ll.addLast("Z"); ll.addFirst("A"); ll.add(1, "A2");

98 System.out.println("Original contents of ll: " + ll);
// remove elements from the linked list ll.remove("F"); ll.remove(2); System.out.println("Contents of ll after deletion: “ + ll); // remove first and last elements ll.removeFirst(); ll.removeLast(); System.out.println("ll after deleting first and last: “ + ll); // get and set a value Object val = ll.get(2); ll.set(2, (String) val + " Changed"); System.out.println("ll after change: " + ll); }

99 The HashSet Class HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage. As most readers likely know, a hash table stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code. The hash code is then used as the index at which the data associated with the key is stored. The transformation of the key into its hash code is performed automatically—you never see the hash code itself. Also, your code can’t directly index the hash table. The advantage of hashing is that it allows the execution time of basic operations, such as add( ), contains( ), remove( ), and size( ), to remain constant even for large sets. The following constructors are defined: HashSet( ) HashSet(Collection c) HashSet(int capacity)

100 10. The first form constructs a default hash set.
11. The second form initializes the hash set by using the elements of c. 12. The third form initializes the capacity of the hash set to capacity. import java.util.*; public class CollectionTest { public static void main(String [] args) System.out.println( "Collection Example!\n" ); int size; // Create a collection HashSet collection = new HashSet (); String str1 = "Yellow", str2 = "White", str3 = "Green", str4 = "Blue"; Iterator iterator; //Adding data in the collection collection.add(str1); collection.add(str2); collection.add(str3); collection.add(str4); System.out.print("Collection data: "); //Create a iterator iterator = collection.iterator(); while (iterator.hasNext()) System.out.print(iterator.next() + " "); } System.out.println();

101 // Get size of a collection
size = collection.size(); if (collection.isEmpty()) { System.out.println("Collection is empty"); } else System.out.println( "Collection size: " + size); System.out.println(); // Remove specific data collection.remove(str2); System.out.println("After removing [" + str2 + "]\n"); System.out.print("Now collection data: "); iterator = collection.iterator(); while (iterator.hasNext()) System.out.print(iterator.next() + " "); System.out.println("Collection size: " + size + "\n"); //Collection empty collection.clear(); { System.out.println( "Collection size: " + size); } } } }

102 The LinkedHashSet Class
Java 2, version 1.4 adds the LinkedHashSet class. This class extends HashSet, but adds no members of its own. LinkedHashSet maintains a linked list of the entries in the set, in the order in which they were inserted. This allows insertion-order iteration over the set. That is, when cycling through a LinkedHashSet using an iterator, the elements will be returned in the order in which they were inserted. This is also the order in which they are contained in the string returned by toString( ) when called on a LinkedHashSet object. To see the effect of LinkedHashSet, try substituting LinkedHashSet For HashSet in the preceding program. The output will be [B, A, D, E, C, F] which is the order in which the elements were inserted.

103 import java.util.LinkedHashSet;
import java.util.Iterator; public class HashSetDemo { public static void main(String[] args) //create object of LinkedHashSet LinkedHashSet lhashSet = new LinkedHashSet(); //add elements to LinkedHashSet object lhashSet.add("1"); lhashSet.add("2"); lhashSet.add("3"); //get the Iterator Iterator itr = lhashSet.iterator(); System.out.println("LinkedHashSet contains : "); while(itr.hasNext()) System.out.println(itr.next()); }

104 The TreeSet Class TreeSet provides an implementation of the Set interface that uses a tree for storage. Objects are stored in sorted, ascending order. Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly. The following constructors are defined: TreeSet( ) TreeSet(Collection c) TreeSet(Comparator comp) TreeSet(SortedSet ss) 5. The first form constructs an empty tree set that will be sorted in ascending order according to the natural order of its elements. 6. The second form builds a tree set that contains the elements of c. 7. The third form constructs an empty tree set that will be sorted according to the comparator specified by comp. 8. The fourth form builds a tree set that contains the elements of ss.

105 import java.util.*; public class TreeSetDemo { public static void main(String[] args) System.out.println("Tree Set Example!\n"); TreeSet tree = new TreeSet(); tree.add("12"); tree.add("23"); tree.add("34"); tree.add("45"); Iterator iterator; iterator = tree.iterator(); System.out.print("Tree set data: "); //Displaying the Tree set data while (iterator.hasNext()) System.out.print(iterator.next() + " "); } System.out.println();

106 //Check impty or not if (tree.isEmpty()) { System.out.print("Tree Set is empty."); } else System.out.println("Tree Set size: " + tree.size()); //Retrieve first data from tree set System.out.println("First data: " + tree.first()); //Retrieve last data from tree set System.out.println("Last data: " + tree.last()); if (tree.remove("23")) System.out.println("Data is removed from tree set"); System.out.println("Data doesn't exist!");

107 System.out.print("Now the tree set contain: ");
iterator = tree.iterator(); //Displaying the Tree set data while (iterator.hasNext()) { System.out.print(iterator.next() + " "); } System.out.println(); System.out.println("Now the size of tree set: " + tree.size()); //Remove all tree.clear(); if (tree.isEmpty()) System.out.print("Tree Set is empty."); else System.out.println("Tree Set size: " + tree.size());

108 Using an Iterator Before you can access a collection through an iterator, you must obtain one. Each of the collection classes provides an iterator( ) method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time. In general, to use an iterator to cycle through the contents of a collection, follow these steps: a. Obtain an iterator to the start of the collection by calling the collection’s iterator( ) method. b. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true. c. Within the loop, obtain each element by calling next( ).

109

110 import java.util.*; class IteratorDemo { public static void main(String args[]) // create an array list ArrayList al = new ArrayList(); // add elements to the array list al.add("C"); al.add("A"); al.add("E"); al.add("B"); al.add("D"); al.add("F"); // use iterator to display contents of al System.out.print("Original contents of al: "); Iterator itr = al.iterator(); while(itr.hasNext()) Object element = itr.next(); System.out.print(element + " "); }

111 System.out.println(); // modify objects being iterated
ListIterator litr = al.listIterator(); while(litr.hasNext()) { Object element = litr.next(); litr.set(element + "+"); } System.out.print("Modified contents of al: "); itr = al.iterator(); while(itr.hasNext()) Object element = itr.next(); System.out.print(element + " "); // now, display the list backwards System.out.print("Modified list backwards: "); while(litr.hasPrevious()) Object element = litr.previous();

112 Working with Maps The Map Interfaces
A map is an object that stores associations between keys and values, or key/value pairs. Given a key, you can find its value. Both keys and values are objects. The keys must be unique, but the values may be duplicated. Some maps can accept a null key and null values, others cannot. The Map Interfaces Interface Description Map Maps unique keys to values. Map.Entry Describes an element (a key/value pair) in a map. This is an inner class of Map. SortedMap Extends Map so that the keys are maintained in ascending order.

113 The Map interface maps unique keys to values.
A key is an object that you use to retrieve a value at a later date. Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key. Several methods throw a NoSuchElementException when no items exist in the invoking map. A ClassCastException is thrown when an object is incompatible with the elements in a map. A NullPointerException is thrown if an attempt is made to use a null object and null is not allowed in the map. An UnsupportedOperationException is thrown when an attempt is made to change an unmodifiable map. 9. Maps revolve around two basic operations: get( ) and put( ). 10. To put a value into a map, use put( ), specifying the key and the value. 11. To obtain a value, call get( ), passing the key as an argument. The value is returned. 12. As mentioned earlier, maps are not collections because they do not implement the Collection interface, but you can obtain a collection-view of a map. 13. To do this, you can use the entrySet( ) method. 14. It returns a Set that contains the elements in the map. 15. To obtain a collection-view of the keys, use keySet( ). 16. To get a collection-view of the values, use values( ). 17. Collection-views are the means by which maps are integrated into the collections framework.

114

115 The SortedMap Interface
The SortedMap interface extends Map. It ensures that the entries are maintained in ascending key order. Several methods throw a NoSuchElementException when no items are in the invoking map. A ClassCastException is thrown when an object is incompatible with the elements in a map. A NullPointerException is thrown if an attempt is made to use a null object when null is not allowed in the map. Sorted maps allow very efficient manipulations of submaps (in other words, a subset of a map). To obtain a submap, use headMap( ), tailMap( ), or subMap( ). To get the first key in the set, call firstKey( ). To get the last key, use lastKey( ).

116 import java.util.*; public class SortedMapExample { public static void main(String[] args) SortedMap map = new TreeMap(); // Add some elements: map.put("2", "Two"); map.put("1", "One"); map.put("5", "Five"); map.put("4", "Four"); map.put("3", "Three"); // Display the lowest key: System.out.println("The lowest key value is: " + map.firstKey()); // Display the highest key: System.out.println("The highest key value is: " + map.lastKey()); // Display All key value System.out.println("All key value is:\n" + map);

117 // Display the headMap:
System.out.println("The head map is:\n" + map.headMap("4")); // Display the tailMap: System.out.println("The tail map is:\n" + map.tailMap("4")); // keySet method returns a Set view of the keys contained in this map. Iterator iterator = map.keySet().iterator(); while (iterator.hasNext()) { Object key = iterator.next(); System.out.println("key : " + key + " value :" + map.get(key)); }

118 The Map Classes Class Description
Several classes provide implementations of the map interfaces. The classes that can be used for maps are summarized here: Class Description AbstractMap Implements most of the Map interface. HashMap Extends AbstractMap to use a hash table. TreeMap Extends AbstractMap to use a tree. WeakHashMap Extends AbstractMap to use a hash table with weak keys. LinkedHashMap Extends HashMap to allow insertion-order iterations. IdentityHashMap Extends AbstractMap and uses reference equality when comparing documents.

119 The HashMap Class 1. The HashMap class uses a hash table to implement the Map interface. 2. This allows the execution time of basic operations, such as get( ) and put( ), to remain constant even for large sets. 3. The following constructors are defined: HashMap( ) HashMap(Map m) HashMap(int capacity)

120 The first form constructs a default hash map.
The second form initializes the hash map by using the elements of m. The third form initializes the capacity of the hash map to capacity. HashMap implements Map and extends AbstractMap. It does not add any methods of its own. You should note that a hash map does not guarantee the order of its elements. Therefore, the order in which elements are added to a hash map is not necessarily the order in which they are read by an iterator. import java.util.*; class HashMapDemo { public static void main(String args[]) // Create a hash map HashMap hm = new HashMap(); // Put elements to the map hm.put("John Doe", new Double( )); hm.put("Tom Smith", new Double(123.22)); hm.put("Jane Baker", new Double( )); hm.put("Todd Hall", new Double(99.22)); hm.put("Ralph Smith", new Double(-19.08));

121 // Get a set of the entries
Set set = hm.entrySet(); // Get an iterator Iterator i = set.iterator(); // Display elements while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } System.out.println(); // Deposit 1000 into John Doe's account double balance = ((Double)hm.get("John Doe")).doubleValue(); hm.put("John Doe", new Double(balance )); System.out.println("John Doe's new balance: " + hm.get("John Doe"));

122 The TreeMap Class The TreeMap class implements the Map interface by using a tree. A TreeMap provides an efficient means of storing key/value pairs in sorted order, and allows rapid retrieval. You should note that, unlike a hash map, a tree map guarantees that its elements will be sorted in ascending key order. The following TreeMap constructors are defined: TreeMap( ) TreeMap(Comparator comp) TreeMap(Map m) TreeMap(SortedMap sm) 4. The first form constructs an empty tree map that will be sorted by using the natural order of its keys. 5. The second form constructs an empty tree-based map that will be sorted by using the Comparator comp. 6. The third form initializes a tree map with the entries from m, which will be sorted by using the natural order of the keys. 7. The fourth form initializes a tree map with the entries from sm, which will be sorted in the same order as sm.

123 import java.util.*; class TreeMapDemo { public static void main(String args[]) // Create a tree map TreeMap tm = new TreeMap(); // Put elements to the map tm.put("John Doe", new Double( )); tm.put("Tom Smith", new Double(123.22)); tm.put("Jane Baker", new Double( )); tm.put("Todd Hall", new Double(99.22)); tm.put("Ralph Smith", new Double(-19.08)); // Get a set of the entries Set set = tm.entrySet(); // Get an iterator Iterator i = set.iterator();

124 The LinkedHashMap Class
// Display elements while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } System.out.println(); // Deposit 1000 into John Doe's account double balance = ((Double)tm.get("John Doe")).doubleValue(); tm.put("John Doe", new Double(balance )); System.out.println("John Doe's new balance: " + tm.get("John Doe")); The LinkedHashMap Class Java 2, version 1.4 adds the LinkedHashMap class. This class extends HashMap. LinkedHashMap maintains a linked list of the entries in the map, in the order in which they were inserted. This allows insertion-order iteration over the map. That is, when iterating a LinkedHashMap, the elements will be returned in the order in which they were inserted. You can also create a LinkedHashMap that returns its elements in the order in which they were last accessed.

125 LinkedHashMap defines the following constructors.
LinkedHashMap(Map m) LinkedHashMap(int capacity) The first form constructs a default LinkedHashMap. The second form initializes the LinkedHashMap with the elements from m. The third form initializes the capacity. import java.util.LinkedHashMap; public class LinkedHashMapExample { public static void main(String[] args) //create object of LinkedHashMap LinkedHashMap lHashMap = new LinkedHashMap(); lHashMap.put("One", new Integer(1)); lHashMap.put("Two", new Integer(2)); //retrieve value using Object get(Object key) method of Java LinkedHashMap class Object obj = lHashMap.get("One"); System.out.println(obj); }

126 int compare(Object obj1, Object obj2)
Comparators Both TreeSet and TreeMap store elements in sorted order. However, it is the comparator that defines precisely what “sorted order” means. By default, these classes store their elements by using what Java refers to as “natural ordering,” which is usually the ordering that you would expect. (A before B, 1 before 2, and so forth.) If you want to order elements a different way, then specify a Comparator object when you construct the set or map. Doing so gives you the ability to govern precisely how elements are stored within sorted collections and maps. The Comparator interface defines two methods: compare( ) and equals( ). The compare( ) method, shown here, compares two elements for order: int compare(Object obj1, Object obj2) 8. obj1 and obj2 are the objects to be compared. 9. This method returns zero if the objects are equal. 10. It returns a positive value if obj1 is greater than obj2. 11. Otherwise, a negative value is returned. 12. The method can throw a ClassCastException if the types of the objects are not compatible for comparison. 13. By overriding compare( ), you can alter the way that objects are ordered. 14. For example, to sort in reverse order, you can create a comparator that reverses the outcome of a comparison.

127 import java.util.*; // A reverse comparator for strings. class MyComp implements Comparator { public int compare(Object a, Object b) String aStr, bStr; aStr = (String) a; bStr = (String) b; // reverse the comparison return bStr.compareTo(aStr); } class CompDemo public static void main(String args[]) // Create a tree set TreeSet ts = new TreeSet(new MyComp());

128 // Add elements to the tree set
ts.add("C"); ts.add("A"); ts.add("B"); ts.add("E"); ts.add("F"); ts.add("D"); // Get an iterator Iterator i = ts.iterator(); // Display elements while(i.hasNext()) { Object element = i.next(); System.out.print(element + " "); } System.out.println();

129 Dictionary Hashtable Properties Stack Vector
The Legacy Classes and Interfaces The legacy classes defined by java.util are shown here: Dictionary Hashtable Properties Stack Vector Vector Vector implements a dynamic array. It is similar to ArrayList, but with two differences: Vector is synchronized, and it contains many legacy methods that are not part of the collections framework. With the release of Java 2, Vector was reengineered to extend AbstractList and implement the List interface, so it now is fully compatible with collections. Here are the Vector constructors: Vector( ) Vector(int size) Vector(int size, int incr) Vector(Collection c)

130 5. The first form creates a default vector, which has an initial size of 10.
6. The second form creates a vector whose initial capacity is specified by size. 7. The third form creates a vector whose initial capacity is specified by size and whose increment is specified by incr. 8. The increment specifies the number of elements to allocate each time that a vector is resized upward. The fourth form creates a vector that contains the elements of collection c. import java.util.*; class VectorDemo { public static void main(String args[]) // initial size is 3, increment is 2 Vector v = new Vector(3, 2); System.out.println("Initial size: " + v.size()); System.out.println("Initial capacity: " + v.capacity()); v.addElement(new Integer(1)); v.addElement(new Integer(2)); v.addElement(new Integer(3)); v.addElement(new Integer(4)); System.out.println("Capacity after four additions: " + v.capacity());

131 v.addElement(new Double(5.45));
System.out.println("Current capacity: " + v.capacity()); v.addElement(new Double(6.08)); v.addElement(new Integer(7)); v.addElement(new Float(9.4)); v.addElement(new Integer(10)); v.addElement(new Integer(11)); v.addElement(new Integer(12)); System.out.println("First element: " + (Integer)v.firstElement()); System.out.println("Last element: " + (Integer)v.lastElement()); if(v.contains(new Integer(10))) System.out.println("Vector contains 3."); // enumerate the elements in the vector. Enumeration vEnum = v.elements(); System.out.println("\nElements in vector:"); while(vEnum.hasMoreElements()) System.out.print(vEnum.nextElement() + " "); System.out.println(); }

132 Stack Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack only defines the default constructor, which creates an empty stack. Stack includes all the methods defined by Vector, and adds several of its own. To put an object on the top of the stack, call push( ). To remove and return the top element, call pop( ). An EmptyStackException is thrown if you call pop( ) when the invoking stack is empty. You can use peek( ) to return, but not remove, the top object. The empty( ) method returns true if nothing is on the stack. The search( ) method determines whether an object exists on the stack, and returns the number of pops that are required to bring it to the top of the stack. import java.util.*; class StackDemo { static void showpush(Stack st, int a) st.push(new Integer(a)); System.out.println("push(" + a + ")"); System.out.println("stack: " + st); } static void showpop(Stack st) System.out.print("pop -> "); Integer a = (Integer) st.pop(); System.out.println(a);

133 public static void main(String args[])
{ Stack st = new Stack(); System.out.println("stack: " + st); showpush(st, 42); showpush(st, 66); showpush(st, 99); showpop(st); try } catch (EmptyStackException e) System.out.println("empty stack");

134 Dictionary Dictionary is an abstract class that represents a key/value storage repository and operates much like Map. Given a key and value, you can store the value in a Dictionary object. Once the value is stored, you can retrieve it by using its key. Thus, like a map, a dictionary can be thought of as a list of key/value pairs. To add a key and a value, use the put( ) method. Use get( ) to retrieve the value of a given key. The keys and values can each be returned as an Enumeration by the keys( ) and elements( ) methods, respectively. The size( ) method returns the number of key/ value pairs stored in a dictionary. isEmpty( ) returns true when the dictionary is empty. You can use the remove( ) method to delete a key/value pair.

135 Hashtable Hashtable was part of the original java.util and is a concrete implementation of a Dictionary. However, Java 2 reengineered Hashtable so that it also implements the Map interface. Thus, Hashtable is now integrated into the collections framework. It is similar to HashMap, but is synchronized. Like HashMap, Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table. The Hashtable constructors are shown here: Hashtable( ) Hashtable(int size) Hashtable(Map m) The first version is the default constructor. The second version creates a hash table that has an initial size specified by size. The Third version creates a hash table that is initialized with the elements in m. The capacity of the hash table is set to twice the number of elements in m.

136 import java.util.*; class HTDemo { public static void main(String args[]) Hashtable balance = new Hashtable(); Enumeration names; String str; double bal; balance.put("John Doe", new Double( )); balance.put("Tom Smith", new Double(123.22)); balance.put("Jane Baker", new Double( )); balance.put("Todd Hall", new Double(99.22)); balance.put("Ralph Smith", new Double(-19.08)); // Show all balances in hash table. names = balance.keys(); while(names.hasMoreElements()) str = (String) names.nextElement(); System.out.println(str + ": " + balance.get(str)); } System.out.println(); // Deposit 1,000 into John Doe's account bal = ((Double)balance.get("John Doe")).doubleValue(); balance.put("John Doe", new Double(bal+1000)); System.out.println("John Doe's new balance: " + balance.get("John Doe"));

137 One important point: like the map classes, Hashtable does not directly support iterators. Thus, the preceding program uses an enumeration to display the contents of balance. However, you can obtain set-views of the hash table, which permits the use of iterators. // Use iterators with a Hashtable. import java.util.*; class HTDemo2 { public static void main(String args[]) Hashtable balance = new Hashtable(); String str; double bal; balance.put("John Doe", new Double( )); balance.put("Tom Smith", new Double(123.22)); balance.put("Jane Baker", new Double( )); balance.put("Todd Hall", new Double(99.22)); balance.put("Ralph Smith", new Double(-19.08)); // show all balances in hashtable Set set = balance.keySet(); // get set-view of keys // get iterator Iterator itr = set.iterator();

138 while(itr.hasNext()) { str = (String) itr.next(); System.out.println(str + ": " + balance.get(str)); } System.out.println(); // Deposit 1,000 into John Doe's account bal = ((Double)balance.get("John Doe")).doubleValue(); balance.put("John Doe", new Double(bal+1000)); System.out.println("John Doe's new balance: " + balance.get("John Doe"));

139 Properties Properties is a subclass of Hashtable.
It is used to maintain lists of values in which the key is a String and the value is also a String. The Properties class is used by many other Java classes. For example, it is the type of object returned by System.getProperties( ) when obtaining environmental values. Properties defines the following instance variable: Properties defaults; This variable holds a default property list associated with a Properties object. Properties defines these constructors: Properties( ) Properties(Properties propDefault) The first version creates a Properties object that has no default values. The second creates an object that uses propDefault for its default values. In both cases, the property list is empty. In addition to the methods that Properties inherits from Hashtable, Properties defines the various methods. Properties also contains one deprecated method: save( ). This was replaced by store( ) because save( ) did not handle errors correctly.

140

141 import java.util.*; class PropDemo { public static void main(String args[]) Properties capitals = new Properties(); Set states; String str; capitals.put("Illinois", "Springfield"); capitals.put("Missouri", "Jefferson City"); capitals.put("Washington", "Olympia"); capitals.put("California", "Sacramento"); capitals.put("Indiana", "Indianapolis"); // Show all states and capitals in hashtable. states = capitals.keySet(); // get set-view of keys Iterator itr = states.iterator(); while(itr.hasNext()) str = (String) itr.next(); System.out.println("The capital of " + str + " is " capitals.getProperty(str) + "."); } System.out.println(); // look for state not in list -- specify default str = capitals.getProperty("Florida", "Not Found"); System.out.println("The capital of Florida is " + str + ".");

142 APPLET CONTROLS

143


Download ppt "APPLETS."

Similar presentations


Ads by Google