Sie sind auf Seite 1von 34

Basic Java Applet Example

1. /*
2. Basic Java Applet Example
3. This Java example shows how to create a basic applet using Java Applet class.
4. */
5.
6. import java.applet.Applet;
7. import java.awt.Graphics;
8.
9. /*
10. <applet code = "BasicAppletExample" width = 200 height = 200>
11. </applet>
12. */
13. public class BasicAppletExample extends Applet{
14.
15. public void paint(Graphics g){
16. //write text using drawString method of Graphics class
17. g.drawString("This is my First Applet",20,100);
18. }
19. }

Java Examples - Display image using


Applet

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

public class appletImage extends Applet {


Image img;
MediaTracker tr;
public void paint(Graphics g) {
tr = new MediaTracker(this);
img = getImage(getCodeBase(), "demoimg.gif");
tr.addImage(img,0);
g.drawImage(img, 0, 0, this);
}
}

Display Image in an Applet Example.


/*
1. Display Image in an Applet Example
2. This Java example shows how to display an image using drawImage method
3. of an Java Graphics class.
4. */
5.
6.
7. import java.applet.Applet;
8. import java.awt.Graphics;
9. import java.awt.Image;
10.
11. /*
12. <applet code = "DisplayImageExample" width = 500 height = 300>
13. <param name = "Image1" value = "one.jpg">
14. <param name = "Image2" value = "two.jpg">
15. </applet>
16. */
17.
18. public class DisplayImageExample extends Applet
19. {
20. Image img1, img2;
21.
22. public void init(){
23.
24. img1 = getImage(getDocumentBase(), getParameter("Image1"));
25. img2 = getImage(getDocumentBase(), getParameter("Image2"));
26. }
27.
28. public void paint(Graphics g){
29.
30. //display an image using drwaImage method of Graphics class.
31. g.drawImage(img1, 0,0,this);
32. g.drawImage(img2, 100,100,this);
33. }
34.
35. }

Draw Oval & Circle in Applet Window


Example
1. /*
2. Draw Oval & Circle in Applet Window Example
3. This java example shows how to draw ovals & circles in an applet window using
4. drawOval method of Graphics class. It also shows how to draw a filled
5. ovals and circles using fillOval method of Graphics class.
6. */
7.
8. /*
9. <applet code="DrawOvalsExample" width=500 height=500>
10. </applet>
11. */
12.
13.
14. import java.applet.Applet;
15. import java.awt.Color;
16. import java.awt.Graphics;
17.
18. public class DrawOvalsExample extends Applet{
19.
20. public void paint(Graphics g){
21.
22. //set color to red
23. setForeground(Color.red);
24.
25. /*
26. * to draw a oval in an applet window use,
27. * void drawOval(int x1,int y1, int width, int height)
28. * method.
29. *
30. * This method draws a oval of specified width and
31. * height at (x1,y1)
32. */
33.
34. //this will draw a oval of width 50 & height 100 at (10,10)
35. g.drawOval(10,10,50,100);
36.
37.
38. /*
39. * To draw a filled oval use
40. * fillOval(int x1,int y1, int width, int height)
41. * method of Graphics class.
42. */
43.
44. //draw filled oval
45. g.fillOval(100,20,50,100);
46.
47. }
48. }

Generate Bouncing Lines Using Applet


Example
1. /*
2. Generate Bouncing Lines Using Applet Example
3. This Java example shows how to create bouncing lines using java Applet
4. example.
5. */
6.
7. import java.awt.*;
8. import java.applet.Applet;
9.
10. public class BouncingLines extends Applet implements Runnable {
11.
12. Thread runner = null;
13.
14. final static int WIDTH = 200;
15. final static int HEIGHT = 100;
16.
17. Image image;
18. Graphics graphics;
19.
20. // bouncing lines member variables
21. int[] x1;
22. int[] y1;
23. int[] x2;
24. int[] y2;
25.
26. int dx1 = 2 + (int)( 3 * Math.random() );
27. int dy1 = 2 + (int)( 3 * Math.random() );
28. int dx2 = 2 + (int)( 3 * Math.random() );
29. int dy2 = 2 + (int)( 3 * Math.random() );
30. static int first = 0;
31. final static int LINES = 50;
32.
33. public void init() {
34.
35. // create arrays to hold the line coordinates
36. x1 = new int[LINES];
37. y1 = new int[LINES];
38. x2 = new int[LINES];
39. y2 = new int[LINES];
40.
41. // initialise the first line
42. x1[0] = (int)( WIDTH * Math.random() );
43. y1[0] = (int)( HEIGHT * Math.random() );
44. x2[0] = (int)( WIDTH * Math.random() );
45. y2[0] = (int)( HEIGHT * Math.random() );
46.
47. // initialise all the other lines
48. for ( int i = 1; i < LINES; i++ ) {
49.
50. x1[i] = x1[0];
51. y1[i] = y1[0];
52. x2[i] = x2[0];
53. y2[i] = y2[0];
54. }
55. image = createImage( WIDTH, HEIGHT );
56. graphics = image.getGraphics();
57. }
58.
59.
60. public void start() {
61.
62. // user visits the page, create a new thread
63. if ( runner == null ) {
64.
65. runner = new Thread( this );
66. runner.start();
67. }
68. }
69.
70.
71. public void stop() {
72.
73. // user leaves the page, stop the thread
74. if ( runner != null && runner.isAlive() )
75. runner.stop();
76.
77. runner = null;
78. }
79.
80.
81. public void run() {
82.
83. while (runner != null) {
84.
85. repaint();
86.
87. try {
88.
89. Thread.sleep( 20 );
90.
91. } catch ( InterruptedException e ) {
92.
93. // do nothing
94. }
95. }
96. }
97.
98.
99. public void paint( Graphics g ) {
100.
101. update( g );
102. }
103.
104.
105. public void update( Graphics g ) {
106.
107. // clear the background to white
108.
109. graphics.setColor( Color.black );
110. graphics.fillRect( 0, 0, WIDTH, HEIGHT );
111.
112. // draw the lines
113. for(int r=4;r<=9;r++)
114. {
115.
116. graphics.setColor( Color.green );
117.
118. int line = first;
119.
120. for ( int i = 0; i < LINES; i++ ) {
121.
122. graphics.drawLine( x1[line], y1[line],
123. x2[line], y2[line] );
124. line++;
125. if ( line == LINES ) line = 0;
126. }
127.
128. line = first;
129.
130. first--;
131.
132. if ( first < 0 ) first = LINES - 1;
133.
134. x1[first] = x1[line];
135. y1[first] = y1[line];
136. x2[first] = x2[line];
137. y2[first] = y2[line];
138.
139. // move the "first" line
140.
141. if (x1[first] + dx2 < WIDTH)
142. x1[first] += dx1;
143. else
144. dx1 = -(2 + (int)( 3 * Math.random() ));
145.
146. if (x1[first] + dx1 >= 0)
147. x1[first] += dx1;
148. else
149. dx1 = 2 + (int)( 3 * Math.random() );
150.
151. if (y1[first] + dy1 < HEIGHT)
152. y1[first] += dy1;
153. else
154. dy1 = -(2 + (int)( 3 * Math.random() ));
155.
156. if (y1[first] + dy1 >= 0)
157. y1[first] += dy1;
158. else
159. dy1 = 2 + (int)( 3 * Math.random() );
160.
161. if (x2[first] + dx2 < WIDTH)
162. x2[first] += dx2;
163. else
164. dx2 = -(2 + (int)( 3 * Math.random() ));
165.
166. if (x2[first] + dx2 >= 0)
167. x2[first] += dx2;
168. else
169. dx2 = 2 + (int)( 3 * Math.random() );
170.
171. if (y2[first] + dy2 < HEIGHT)
172. y2[first] += dy2;
173. else
174. dy2 = -(2 + (int)( 3 * Math.random() ));
175.
176. if (y2[first] + dy2 >= 0)
177. y2[first] += dy2;
178. else
179. dy2 = 2 + (int)( 3 * Math.random() );
180.
181. // copy buffer to screen
182. g.drawImage( image, 0, 0, this );
183. }
184. }
185. }

Get Background Color Of an Applet Window


Example
1. /*
2. Get Background Color Of an Applet Window Example
3. This java example shows how to get background color of an Applet window using
4. getBackground method of component class.
5. */
6.
7. /*
8. <applet code="GetBackGroundColorExample" width=200 height=200>
9. </applet>
10. */
11.
12.
13. import java.applet.Applet;
14. import java.awt.Color;
15. import java.awt.Graphics;
16.
17. public class GetBackGroundColorExample extends Applet{
18.
19. public void paint(Graphics g){
20. //get background color using getBackground method
21. Color c = getBackground();
22. g.drawString(c.toString(),50,50);
23. }
24. }

Get Foreground Color Of an Applet Window Example


1. /*
2. Get Foreground Color Of an Applet Window Example
3. This java example shows how to get foreground color of an Applet window using
4. getForeground method of component class.
5. */
6.
7. /*
8. <applet code="GetForegroundColorExample" width=200 height=200>
9. </applet>
10. */
11.
12.
13. import java.applet.Applet;
14. import java.awt.Color;
15. import java.awt.Graphics;
16.
17.
18. public class GetForgroundColorExample extends Applet{
19.
20. public void paint(Graphics g){
21. /*
22. * Get Foreground color of an applet using
23. * Color getForeground() method of Component class.
24. */
25.
26. Color c = getForeground();
27. g.drawString(c.toString(),50,50);
28. }
29. }

Set Status Message in Applet Window


Example
1. /*
2. Set Status Message in Applet Window Example
3. This java example shows how to set a status message of an applet window
4. using showStatus method of an Applet class.
5. */
6.
7. /*
8. <applet code="SetStatusMessageExample" width=200 height=200>
9. </applet>
10. */
11.
12.
13. import java.applet.Applet;
14. import java.awt.Graphics;
15.
16. public class SetStatusMessageExample extends Applet{
17.
18. public void paint(Graphics g){
19. /*
20. * Show status message in an Applet window using
21. * void showStatus(String msg) method of an applet class.
22. */
23.
24. //this will be displayed inside an applet
25. g.drawString("Show Status Example", 50, 50);
26.
27. //this will be displayed in a status bar of an applet window
28. showStatus("This is a status message of an applet window");
29. }
30. }

Java Examples - Play sound using


Applet?
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class PlaySoundApplet extends Applet implements ActionListener {


Button play,stop;
AudioClip audioClip;

public void init() {


play = new Button(" Play in Loop ");
add(play);
play.addActionListener(this);
stop = new Button(" Stop ");
add(stop);
stop.addActionListener(this);
audioClip = getAudioClip(getCodeBase(), "Sound.wav");
}
public void actionPerformed(ActionEvent ae) {
Button source = (Button)ae.getSource();
if (source.getLabel() == " Play in Loop ") {
audioClip.play();
} else if(source.getLabel() == " Stop "){
audioClip.stop();
}
}
}

Java Examples - Swing applet in JAVA?


import javax.swing.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class SApplet extends Applet implements ActionListener {


TextField input,output;
Label label1,label2;
Button b1;
JLabel lbl;
int num, sum = 0;

public void init() {


label1 = new Label("please enter number : ");
add(label1);
label1.setBackground(Color.yellow);
label1.setForeground(Color.magenta);
input = new TextField(5);

add(input);
label2 = new Label("Sum : ");

add(label2);
label2.setBackground(Color.yellow);
label2.setForeground(Color.magenta);
output = new TextField(20);

add(output);
b1 = new Button("Add");
add(b1);
b1.addActionListener(this);
lbl = new JLabel("Swing Applet Example. ");
add(lbl);
setBackground(Color.yellow);
}
public void actionPerformed(ActionEvent ae ){
try {
num = Integer.parseInt(input.getText());
sum = sum+num;
input.setText("");
output.setText(Integer.toString(sum));
lbl.setForeground(Color.blue);
lbl.setText("Output of the second Text Box : " + output.getText());
} catch(NumberFormatException e) {
lbl.setForeground(Color.red);
lbl.setText("Invalid Entry!");
}
}
}

Java Examples - Create eventlistener


in Applet
import java.applet.*;
import java.awt.event.*;
import java.awt.*;

public class EventListeners extends Applet implements ActionListener {


TextArea txtArea;
String Add, Subtract;
int i = 10, j = 20, sum = 0, Sub = 0;

public void init() {


txtArea = new TextArea(10,20);
txtArea.setEditable(false);
add(txtArea,"center");
Button b = new Button("Add");
Button c = new Button("Subtract");
b.addActionListener(this);
c.addActionListener(this);
add(b);
add(c);
}
public void actionPerformed(ActionEvent e) {
sum = i + j;
txtArea.setText("");
txtArea.append("i = "+ i + "\t" + "j = " + j + "\n");
Button source = (Button)e.getSource();

if(source.getLabel() == "Add") {
txtArea.append("Sum : " + sum + "\n");
}
if(i >j) {
Sub = i - j;
} else {
Sub = j - i;
}
if(source.getLabel() == "Subtract") {
txtArea.append("Sub : " + Sub + "\n");
}
}
}

Java Examples - Fill colors using


Applet?
import java.applet.*;
import java.awt.*;

public class fillColor extends Applet {


public void paint(Graphics g) {
g.drawRect(300,150,200,100);
g.setColor(Color.yellow);
g.fillRect( 300,150, 200, 100 );
g.setColor(Color.magenta);
g.drawString("Rectangle",500,150);
}
}

Timer Applet
Timer Applet

import java.applet.*;

import java.awt.*;

public class TimerApplet extends Applet implements Runnable

private String msg2 = new String("");

private int secs;

private int mins;

private int hrs;

private Thread clock;

public int time =300000;

public void destroy()

clock.stop();

}
public void init()

String parameter;

if(clock == null)

clock = new Thread(this);

clock.start();

public void paint(Graphics gr)

++secs;

if(secs == 60)

mins++;

secs = 0;

if(mins == 60)

hrs++;

secs = 0;

mins = 0;

//gr.setFont(bigFont);
gr.setColor(Color.red);

//gr.drawString(msg1,10,100);

gr.drawString(" "+ hrs + " Hours " + mins + " Minutes " + secs + " Seconds", 10, 130);

gr.drawString(msg2,10,150);

setBackground(Color.black);

public void run()

while(true)

repaint();

try

clock.sleep(1000);

catch(InterruptedException e)

public void start()

clock.resume();

}
public void stop()

clock.suspend();

Displaying Graphics in Applet


Commonly used methods of Graphics class:
1. public abstract void drawString(String str, int x, int y): is used to draw the
specified string.

2. public void drawRect(int x, int y, int width, int height): draws a rectangle
with the specified width and height.

3. public abstract void fillRect(int x, int y, int width, int height): is used to fill
rectangle with the default color and specified width and height.

4. public abstract void drawOval(int x, int y, int width, int height): is used to
draw oval with the specified width and height.

5. public abstract void fillOval(int x, int y, int width, int height): is used to fill
oval with the default color and specified width and height.

6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw
line between the points(x1, y1) and (x2, y2).

7. public abstract boolean drawImage(Image img, int x, int y,


ImageObserver observer): is used draw the specified image.

8. public abstract void drawArc(int x, int y, int width, int height, int
startAngle, int arcAngle): is used draw a circular or elliptical arc.

9. public abstract void fillArc(int x, int y, int width, int height, int
startAngle, int arcAngle): is used to fill a circular or elliptical arc.

10. public abstract void setColor(Color c): is used to set the graphics current
color to the specified color.

11. public abstract void setFont(Font font): is used to set the graphics current
font to the specified font.

Example of Graphics in applet:

1. import java.applet.Applet;
2. import java.awt.*;
3.
4. public class GraphicsDemo extends Applet{
5.
6. public void paint(Graphics g){
7. g.setColor(Color.red);
8. g.drawString("Welcome",50, 50);
9. g.drawLine(20,30,20,300);
10. g.drawRect(70,100,30,30);
11. g.fillRect(170,100,30,30);
12. g.drawOval(70,200,30,30);
13.
14. g.setColor(Color.pink);
15. g.fillOval(170,200,30,30);
16. g.drawArc(90,150,30,30,30,270);
17. g.fillArc(270,150,30,30,0,180);
18.
19. }
20. }

myapplet.html
1. <html>
2. <body>
3. <applet code="GraphicsDemo.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Displaying Image in Applet


Applet is mostly used in games and animation. For this purpose image is required to be
displayed. The java.awt.Graphics class provide a method drawImage() to display the
image.

Syntax of drawImage() method:


1. public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used draw the specified image.

How to get the object of Image:


The java.applet.Applet class provides getImage() method that returns the object of
Image. Syntax:

1. public Image getImage(URL u, String image){}

Other required methods of Applet class to display


image:
1. public URL getDocumentBase(): is used to return the URL of the document
in which applet is embedded.

2. public URL getCodeBase(): is used to return the base URL.

Example of displaying image in applet:

1. import java.awt.*;
2. import java.applet.*;
3.
4.
5. public class DisplayImage extends Applet {
6.
7. Image picture;
8.
9. public void init() {
10. picture = getImage(getDocumentBase(),"sonoo.jpg");
11. }
12.
13. public void paint(Graphics g) {
14. g.drawImage(picture, 30,30, this);
15. }
16.
17. }
In the above example, drawImage() method of Graphics class is used to display the
image. The 4th argument of drawImage() method of is ImageObserver object. The
Component class implements ImageObserver interface. So current class object would
also be treated as ImageObserver because Applet class indirectly extends the
Component class.

myapplet.html
1. <html>
2. <body>
3. <applet code="DisplayImage.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Animation in Applet
Applet is mostly used in games and animation. For this purpose image is required to
be moved.

Example of animation in applet:


1. import java.awt.*;
2. import java.applet.*;
3. public class AnimationExample extends Applet {
4.
5. Image picture;
6.
7. public void init() {
8. picture =getImage(getDocumentBase(),"bike_1.gif");
9. }
10.
11. public void paint(Graphics g) {
12. for(int i=0;i<500;i++){
13. g.drawImage(picture, i,30, this);
14.
15. try{Thread.sleep(100);}catch(Exception e){}
16. }
17. }
18. }
In the above example, drawImage() method of Graphics class is used to display the
image. The 4th argument of drawImage() method of is ImageObserver object. The
Component class implements ImageObserver interface. So current class object would
also be treated as ImageObserver because Applet class indirectly extends the
Component class.
myapplet.html
1. <html>
2. <body>
3. <applet code="DisplayImage.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

EventHandling in Applet
As we perform event handling in AWT or Swing, we can perform it in applet also. Let's
see the simple example of event handling in applet that prints a message by click on
the button.

Example of EventHandling in applet:

1. import java.applet.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class EventApplet extends Applet implements ActionListener{
5. Button b;
6. TextField tf;
7.
8. public void init(){
9. tf=new TextField();
10. tf.setBounds(30,40,150,20);
11.
12. b=new Button("Click");
13. b.setBounds(80,150,60,50);
14.
15. add(b);add(tf);
16. b.addActionListener(this);
17.
18. setLayout(null);
19. }
20.
21. public void actionPerformed(ActionEvent e){
22. tf.setText("Welcome");
23. }
24. }
In the above example, we have created all the controls in init() method because it is
invoked only once.

myapplet.html
1. <html>
2. <body>
3. <applet code="EventApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

JApplet class in Applet


As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of
swing. The JApplet class extends the Applet class.

Example of EventHandling in JApplet:

1. import java.applet.*;
2. import javax.swing.*;
3. import java.awt.event.*;
4. public class EventJApplet extends JApplet implements ActionListener{
5. JButton b;
6. JTextField tf;
7. public void init(){
8.
9. tf=new JTextField();
10. tf.setBounds(30,40,150,20);
11.
12. b=new JButton("Click");
13. b.setBounds(80,150,70,40);
14.
15. add(b);add(tf);
16. b.addActionListener(this);
17.
18. setLayout(null);
19. }
20.
21. public void actionPerformed(ActionEvent e){
22. tf.setText("Welcome");
23. }
24. }
In the above example, we have created all the controls in init() method because it is
invoked only once.

myapplet.html
1. <html>
2. <body>
3. <applet code="EventJApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Painting in Applet
We can perform painting operation in applet by the mouseDragged() method of
MouseMotionListener.

Example of Painting in Applet:

1. import java.awt.*;
2. import java.awt.event.*;
3. import java.applet.*;
4. public class MouseDrag extends Applet implements MouseMotionListener{
5.
6. public void init(){
7. addMouseMotionListener(this);
8. setBackground(Color.red);
9. }
10.
11. public void mouseDragged(MouseEvent me){
12. Graphics g=getGraphics();
13. g.setColor(Color.white);
14. g.fillOval(me.getX(),me.getY(),5,5);
15. }
16. public void mouseMoved(MouseEvent me){}
17.
18. }
In the above example, getX() and getY() method of MouseEvent is used to get the
current x-axis and y-axis. The getGraphics() method of Component class returns the
object of Graphics.

myapplet.html
1. <html>
2. <body>
3. <applet code="MouseDrag.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose, Applet
class provides a method named getParameter(). Syntax:

1. public String getParameter(String parameterName)

Example of using parameter in Applet:

1. import java.applet.Applet;
2. import java.awt.Graphics;
3.
4. public class UseParam extends Applet{
5.
6. public void paint(Graphics g){
7. String str=getParameter("msg");
8. g.drawString(str,50, 50);
9. }
10.
11. }
myapplet.html
1. <html>
2. <body>
3. <applet code="UseParam.class" width="300" height="300">
4. <param name="msg" value="Welcome to applet">
5. </applet>
6. </body>
7. </html>

Applet Communication
java.applet.AppletContext class provides the facility of communication between applets.
We provide the name of applet through the HTML file. It provides getApplet() method
that returns the object of Applet. Syntax:

1. public Applet getApplet(String name){}

Example of Applet Communication

1. import java.applet.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class ContextApplet extends Applet implements ActionListener{
5. Button b;
6.
7. public void init(){
8. b=new Button("Click");
9. b.setBounds(50,50,60,50);
10.
11. add(b);
12. b.addActionListener(this);
13. }
14.
15. public void actionPerformed(ActionEvent e){
16.
17. AppletContext ctx=getAppletContext();
18. Applet a=ctx.getApplet("app2");
19. a.setBackground(Color.yellow);
20. }
21. }
myapplet.html
1. <html>
2. <body>
3. <applet code="ContextApplet.class" width="150" height="150" name="app1">
4. </applet>
5.
6. <applet code="First.class" width="150" height="150" name="app2">
7. </applet>
8. </body>
9. </html>
next prev

Java List Interface


List Interface is the subinterface of Collection.It contains methods to insert and delete
elements in index basis.It is a factory of ListIterator interface.

List Interface declaration


1. public interface List<E> extends Collection<E>

Methods of Java List Interface


Method Description

void add(int index,Object It is used to insert element into the invoking list at the ind
element)

boolean addAll(int It is used to insert all elements of c into the invoking list
index,Collection c) index.

object get(int index) It is used to return the object stored at the specified
collection.

object set(int index,Object It is used to assign element to the location specified by ind
element)

object remove(int index) It is used to remove the element at position index from t
the deleted element.

ListIterator listIterator() It is used to return an iterator to the start of the invoking l

ListIterator listIterator(int index) It is used to return an iterator to the invoking list that beg

Java List Example


1. import java.util.*;
2. public class ListExample{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Amit");
6. al.add("Vijay");
7. al.add("Kumar");
8. al.add(1,"Sachin");
9. System.out.println("Element at 2nd position: "+al.get(2));
10. for(String s:al){
11. System.out.println(s);
12. }
13. }
14. }

Output:

Element at 2nd position: Vijay


Amit
Sachin
Vijay
Kumar

Java ListIterator Interface


ListIterator Interface is used to traverse the element in backward and forward
direction.

ListIterator Interface declaration


1. public interface ListIterator<E> extends Iterator<E>

Methods of Java ListIterator Interface:


Method Description

boolean hasNext() This method return true if the list iterator has more elements when
forward direction.

Object next() This method return the next element in the list and advances the curso

boolean This method return true if this list iterator has more elements when
hasPrevious() reverse direction.
Object previous() This method return the previous element in the list and moves the cur

Example of ListIterator Interface


1. import java.util.*;
2. public class TestCollection8{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Amit");
6. al.add("Vijay");
7. al.add("Kumar");
8. al.add(1,"Sachin");
9. System.out.println("element at 2nd position: "+al.get(2));
10. ListIterator<String> itr=al.listIterator();
11. System.out.println("traversing elements in forward direction...");
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. System.out.println("traversing elements in backward direction...");
16. while(itr.hasPrevious()){
17. System.out.println(itr.previous());
18. }
19. }
20. }
Test it Now

Output:

element at 2nd position: Vijay


traversing elements in forward direction...
Amit
Sachin
Vijay
Kumar
traversing elements in backward direction...
Kumar
Vijay
Sachin
Amit
Example of ListIterator Interface: Book
1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class ListExample {
15. public static void main(String[] args) {
16. //Creating list of Books
17. List<Book> list=new ArrayList<Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Gra
w Hill",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to list
23. list.add(b1);
24. list.add(b2);
25. list.add(b3);
26. //Traversing list
27. for(Book b:list){
28. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity
);
29. }
30. }
31. }

Output:

101 Let us C Yashwant Kanetkar BPB 8


102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6
Java TreeMap class

Java TreeMap class implements the Map interface by using a tree. It provides an efficient
means of storing key/value pairs in sorted order.

The important points about Java TreeMap class are:

o A TreeMap contains values based on the key. It implements the NavigableMap


interface and extends AbstractMap class.

o It contains only unique elements.

o It cannot have null key but can have multiple null values.

o It is same as HashMap instead maintains ascending order.

TreeMap class declaration


Let's see the declaration for java.util.TreeMap class.

1. public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K


,V>, Cloneable, Serializable

TreeMap class Parameters


Let's see the Parameters for java.util.TreeMap class.

o K: It is the type of keys maintained by this map.

o V: It is the type of mapped values.


Constructors of Java TreeMap class
Constructor Description

TreeMap() It is used to construct an empty tree map that will be sorted using t
key.

TreeMap(Comparator It is used to construct an empty tree-based map that will be sorted


comp) comp.

TreeMap(Map m) It is used to initialize a tree map with the entries from m, which wi
natural order of the keys.

TreeMap(SortedMap sm) It is used to initialize a tree map with the entries from the SortedM
sorted in the same order as sm.

Methods of Java TreeMap class


Method Description

boolean containsKey(Object key) It is used to return true if this map contains a mapping for t

boolean containsValue(Object It is used to return true if this map maps one or more
value) value.

Object firstKey() It is used to return the first (lowest) key currently in this so

Object get(Object key) It is used to return the value to which this map maps the sp

Object lastKey() It is used to return the last (highest) key currently in this so

Object remove(Object key) It is used to remove the mapping for this key from this Tree

void putAll(Map map) It is used to copy all of the mappings from the specified ma
Set entrySet() It is used to return a set view of the mappings contained in

int size() It is used to return the number of key-value mappings in th

Collection values() It is used to return a collection view of the values contained

Java TreeMap Example:


1. import java.util.*;
2. class TestCollection15{
3. public static void main(String args[]){
4. TreeMap<Integer,String> hm=new TreeMap<Integer,String>();
5. hm.put(100,"Amit");
6. hm.put(102,"Ravi");
7. hm.put(101,"Vijay");
8. hm.put(103,"Rahul");
9. for(Map.Entry m:hm.entrySet()){
10. System.out.println(m.getKey()+" "+m.getValue());
11. }
12. }
13. }
Test it Now

Output:100 Amit
101 Vijay
102 Ravi
103 Rahul

Java TreeMap Example: remove()


1. import java.util.*;
2. public class TreeMapExample {
3. public static void main(String args[]) {
4. // Create and populate tree map
5. Map<Integer, String> map = new TreeMap<Integer, String>();
6. map.put(102,"Let us C");
7. map.put(103, "Operating System");
8. map.put(101, "Data Communication and Networking");
9. System.out.println("Values before remove: "+ map);
10. // Remove value for key 102
11. map.remove(102);
12. System.out.println("Values after remove: "+ map);
13. }
14. }

Output:

Values before remove: {101=Data Communication and Networking, 102=Let us C,


103=Operating System}
Values after remove: {101=Data Communication and Networking, 103=Operating
System}

What is difference between HashMap and TreeMap?


HashMap TreeMap

1) HashMap can contain one null key. TreeMap can not contain any null key

2) HashMap maintains no order. TreeMap maintains ascending order.

Java TreeMap Example: Book


1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class MapExample {
15. public static void main(String[] args) {
16. //Creating map of Books
17. Map<Integer,Book> map=new TreeMap<Integer,Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw
Hill",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to map
23. map.put(2,b2);
24. map.put(1,b1);
25. map.put(3,b3);
26.
27. //Traversing map
28. for(Map.Entry<Integer, Book> entry:map.entrySet()){
29. int key=entry.getKey();
30. Book b=entry.getValue();
31. System.out.println(key+" Details:");
32. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity
);
33. }
34. }
35. }

Output:

1 Details:
101 Let us C Yashwant Kanetkar BPB 8
2 Details:
102 Data Communications & Networking Forouzan Mc Graw Hill 4
3 Details:
103 Operating System Galvin Wiley 6