Cursors of Collection Framework in Java
Cursors of Collection Framework in Java
- Cursors of Collection Framework in Java
- Iterator Cursors of Collection Framework in Java
- ListIterator Cursors of Collection Framework
- Enumeration Cursors in Java
- Comparison Between Iterator, ListIterator and Enumeration Cursors in Java
Cursors of Collection Framework in Java:
Cursors are mainly used to access the elements of any collection. We have the following three types of cursors in Collection Framework:
Iterator Cursors of Collection Framework in Java
This cursor is used to access the elements in the forward direction only. This cursor can be applied to any Collection Interfaces. While accessing the methods we can also delete the elements. An iterator is an interface and we cannot create an object directly. If we want to create an object for Iterator we have to use the iterator() method.
Creation of Iterator
Syntax : Iterator it = c.iterator();
Here, the iterator() method internally creates and returns an object of a class that implements the Iterator Interface.
Methods of Iterator:
- boolean hasNext(): returns true if there is a next element in the array list.
- Object next(): returns the next element in the array list.
- void remove(): removes an element from an array list.
Sample Program to demonstrate Iterator Cursors in Java
import java.util.*; public class IteratorDemo < public static void main (String[]args) < LinkedList < Integer >ll = new LinkedList < Integer >(); ll.add (10); ll.add (25); ll.add (50); ll.add (20); ll.add (25); ll.add (23); ll.add (60); ll.add (25); ll.add (30); ll.add (40); ll.add (15); ll.add (25); System.out.println (ll); Iterator it = ll.descendingIterator (); while (it.hasNext ()) < System.out.println (it.next ()); >Iterator it1 = ll.descendingIterator (); while (it1.hasNext ()) < Integer e = (Integer) it1.next (); //down casting if (e == 25) < it1.remove (); >> System.out.println (ll); > >
ListIterator Cursors of Collection Framework in Java
This cursor is used to access the elements of Collection in both forward and backward directions. This cursor can be applied only for List category Collections. While accessing the methods we can also add, set, delete elements. ListIterator is an interface and we cannot create Object directly. If we want to create an object for ListIterator we have to use ListIterator() method.
Creation of ListIterator
Syntax : ListIterator it = l.listIterator();
Here, listIterator() method internally creates and returns an object of a class that implements the ListIterator Interface.
Methods of ListIterator:
- boolean hasNext(): return true if the given list iterator contains more number of elements during traversing the given list in the forward direction.
- Object next(): return the next element in the given list. This method is used to iterate through the list.
- boolean hasPrevious(): is used to retrieve and remove the head of the deque.
- Object previous(): return the previous element from the list and moves the cursor in a backward position. The above method can be used to iterate the list in a backward direction.
- int nextIndex(): return the index of the element which is returned by the next() method.
- int previousIndex(): return the index of the given element which is returned by a call to previous. The method may return -1 if and only if the iterator is placed at the beginning of the list.
- void remove(): remove the last element from the list which is returned by next() or previous() method.
- void set(Object obj): is used to replace the last element which is returned by the next() or previous() along with the given element.
- void add(Object obj): is used to insert the given element into the specified list. The element is inserted automatically before the next element may return by the next() method.
Sample Program to demonstrate ListIterator Cursors of Collection Framework in Java
import java.util.LinkedList; import java.util.ListIterator; public class ListIteratorDemo < public static void main (String[]args) < LinkedList < Integer >ll = new LinkedList < Integer >(); ll.add (10); ll.add (25); ll.add (50); ll.add (20); ll.add (25); ll.add (23); ll.add (40); ll.add (15); ll.add (25); System.out.println (ll); ListIterator < Integer >lit = ll.listIterator (); System.out.println ("Elements in Forward Direction"); while (lit.hasNext ()) < System.out.println (lit.next () + " "); >System.out.println ("\n elements in Backward direction"); while (lit.hasPrevious ()) < System.out.println (lit.previous () + " "); >while (lit.hasNext ()) < Object o = lit.next (); Integer e = (Integer) o; if (e == 23) < lit.add (56); >if (e == 15) < lit.set (15000); >if (e == 25) < lit.remove (); >> System.out.println ("\n New List:" + ll); > >
Enumeration Cursors of Collection Framework in Java
This cursor is used to access the elements of Collection only in a forward direction. This is a legacy cursor and can be applied only for legacy classes like Vector, Stack, Hashtable. Enumeration is also an interface and we cannot create the object directly. If we want to create an object for Enumeration we have to use a legacy method called the elements() method. The Enumeration interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects.
Creation of Enumeration
Syntax : Enumeration e = v.elements();
Here, the elements() method internally creates and returns an object of a class that implements the Enumeration Interface.
Methods of Enumeration
- boolean hasMoreElements(): When implemented, it must return true while there are still more elements to extract, and false when all the elements have been enumerated.
- Object nextElement(): This returns the next object in the enumeration as a generic Object reference.
Program to demonstrate Enumeration Cursors of Collection Framework in Java
import java.util.*; public class EnumerationDemo < public static void main(String[] args) < Vectorv = new Vector(); v.add(10); v.add(25); v.add(50); v.add(20); v.add(25); v.add(23); v.add(25); System.out.println(v); Enumeration e = v.elements(); while(e.hasMoreElements()) < System.out.println(e.nextElement()+" "); >> >
Comparison Between Iterator, ListIterator and Enumeration Cursors in Java
In the next article, I am going to discuss Set Collections in Java with examples. Here, in this article, I try to explain Cursors of Collection Framework in Java and I hope you enjoy this Cursors of Collection Framework in Java article.
Swing Cursors
Swing Cursors can be defined as point or indicator on the screen, it is used to select the input from the system that user operates with mouse. Three types of Swing Cursors are available in java collection framework to retrieve the elements from the collection.
Enumeration is used to retrieve the objects one by one from the collection framework by elements method as follows. [java]Enumeration e=v.elements();[/java] Where v can be any vector object. Enumeration is only used for legacy classes and developer can perform only read operation. Iterator is used to overcome the limitations of the enumeration. It is universal cursor and developer can perform both read and remove operations.Creation of object to iterator is possible with iterator() as follows. [java]public Iterator iterator();[/java]Iterator is only for one direction cursor. ListIterator is used to overcome the limitations of both enumeration and iteration. In iterator and enumeration only forward direction of cursor is available where as in ListIterator both forward and backward directions are available.Replacement and addition of objects is possible in ListIterator to perform read and remove operations. In forward and backward direction it follows methods as follows. [java]public void next();//in forward direction. public void previous();//in backward directions.[/java]
Types of cursors
- Default
- Hand
- Wait
- Pointer
- Cross-hair
- No-drop
- Not-allowed, etc.
Creating a Cursor
Example
The below example shows how to create a cursor by using Swing components. HowToCreateCursor.java [java]package swing; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Toolkit; import javax.swing.JFrame; public class HowToCreateCursor < public static void main(String[] args) < JFrame aWindow = new JFrame("Create a Cursor"); Toolkit theKit = aWindow.getToolkit(); Dimension wndSize = theKit.getScreenSize(); aWindow.setBounds(wndSize.width / 4, wndSize.height / 4, // Position wndSize.width / 2, wndSize.height / 2); // Size aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); aWindow.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); aWindow.setVisible(true); >>[/java] Create the title of the window, size and include window tool kit to inherit the properties. [java]JFrame aWindow = new JFrame(«Create a Cursor»); Toolkit theKit = aWindow.getToolkit(); // Get the window toolkit Dimension wndSize = theKit.getScreenSize()[/java] Set the place of the application on the screen. [java]aWindow.setBounds(wndSize.width / 4, wndSize.height / 4, // Position wndSize.width / 2, wndSize.height / 2); // Size[/java] Include the cursor name in the method and display the method. [java]aWindow.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); aWindow.setVisible(true); // Display the window[/java] Output: Output will be as follows with cross hair cursor in the window.
Change the Cursor
Example
The below example shows how to change the shape of the cursor by extending JFrame. ChangeCursorShape.java [java]package swing;//create a package import java.awt.Cursor; import javax.swing.JFrame; import javax.swing.SwingUtilities; public class ChangeCursorShape extends JFrame < public static void main(String[] args) < SwingUtilities.invokeLater(new Runnable() < public void run() < ChangeCursorShape mainForm = new ChangeCursorShape(); mainForm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainForm.setSize(250, 250); Cursor cursor = new Cursor(Cursor.HAND_CURSOR); mainForm.setCursor(cursor); mainForm.pack(); mainForm.setVisible(true); >>); > >[/java] Create a package and import all the required packages from Swing API. [java]package swing;//create a package import java.awt.Cursor; import javax.swing.JFrame; import javax.swing.SwingUtilities;[/java] Create a class that should extend the JFrame and invoke new runnable object to initialize the graphical user interface. [java]package swing;//create a package import java.awt.Cursor; import javax.swing.JFrame; import javax.swing.SwingUtilities; public class ChangeCursorShape extends JFrame < public static void main(String[] args) < SwingUtilities.invokeLater(new Runnable() < public void run() <[/java] Create object to the class and add size to the window with object. [java]ChangeCursorShape mainForm = new ChangeCursorShape(); mainForm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainForm.setSize(250, 250);[/java] Create any cursor like HAND CURSOR and set the cursor in object. [java]Cursor cursor = new Cursor(Cursor.HAND_CURSOR); mainForm.setCursor(cursor);[/java] Output: Output will be as follows with hand cursor in the window.
Wait Cursor
Example
This example shows how to create the redirecting cursor with swing components. WaitCursor.java [java]package swing; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class WaitCursor implements ActionListener < private JFrame frame; private String defaultButtonText = "Show Wait Cursor"; private JButton button = new JButton(defaultButtonText); private Cursor waitCursor = new Cursor(Cursor.WAIT_CURSOR); private Cursor defaultCursor = new Cursor(Cursor.DEFAULT_CURSOR); private boolean waitCursorIsShowing; public static void main(String[] args) < new WaitCursor(); >public WaitCursor() < // add actionlistener on the button button.addActionListener(this); frame = new JFrame(" Wait Cursor Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(button); frame.setPreferredSize(new Dimension(400,300)); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); >public void actionPerformed(ActionEvent evt) < if (waitCursorIsShowing) < waitCursorIsShowing = false; button.setText(defaultButtonText); frame.setCursor(defaultCursor); >else < waitCursorIsShowing = true; button.setText("Back to Default Cursor"); frame.setCursor(waitCursor); >> > [/java] Create a package and import all the required packages. [java]package swing; import java.awt.*; import java.awt.event.*; import javax.swing.*;[/java] Create a class that should implements the ActionListener and add title to the window, set the default button, set the default cursor. [java]public class WaitCursor implements ActionListener < private JFrame frame; private String defaultButtonText = "Show Wait Cursor"; private JButton button = new JButton(defaultButtonText); private Cursor waitCursor = new Cursor(Cursor.WAIT_CURSOR); private Cursor defaultCursor = new Cursor(Cursor.DEFAULT_CURSOR); private boolean waitCursorIsShowing;[/java] Add ActionListener on the button. [java]button.addActionListener(this);[/java] To change the cursor back to the default place. [java] waitCursorIsShowing = false; button.setText(defaultButtonText); frame.setCursor(defaultCursor);[/java] To change the cursor to the wait cursor mode. [java] waitCursorIsShowing = true; button.setText("Back to Default Cursor"); frame.setCursor(waitCursor);[/java] Output: Output will be as follows with wait icon is spinning. When click on Back to Default Cursor it comes to normal state.
Using cursors and getting result in Oracle PL/SQL with Java/JDBC
How can I run this query from a java code using jdbc and get the resultset? I have tried running the query without using cursor, and its running correctly. I couldn’t figure out a way to do this in java code. If I run the query directly onto oracle client, it works with no problems. So there is no problem with the query. P.S. I dont want to store the code as stored procedure and call that due to some constraints.
4 Answers 4
Could you try below method:
To retrieve the cursor you should declare it as a REF CURSOR in Package spec.
--Creating the REF CURSOR type type g_cursor is ref cursor;
In both, spec and body, you need declare an out REF CURSOR variable in procedure signature, how cited above.
procedure PRO_RETURN_CARS( i_id in tbl_car.car_id%type, o_cursor in out g_cursor);
The cursor must be opened in procedure’s body to return, this way:
open o_cursor for select car_id, company, model, color, hp, price from tbl_car where car_id = i_id;
create or replace package PAC_CURSOR is --Creating REF CURSOR type type g_cursor is ref cursor; --Procedure that return the cursor procedure PRO_RETURN_CARS( i_id in tbl_car.car_id%type, o_cursor in out g_cursor); -- Our cursor end PAC_CURSOR; / create or replace package body PAC_CURSOR is procedure PRO_RETURN_CARS( i_id in tbl_car.car_id%type, o_cursor in out g_cursor) is begin --Opening the cursor to return matched rows open o_cursor for select car_id, company, model, color, hp, price from tbl_car where car_id = i_id; end PRO_RETURN_CARS; end PAC_CURSOR;
We have Oracle side ready, now we need create Java call
How the cursors are being returned by a procedure, we’ll used a java.sql.CallableStatement instance:
CallableStatement cs = conn.prepareCall("");
The registerOutParameter will obtain oracle.jdbc.OracleTypes.CURSOR type and return a java.sql.ResultSet instance. We can iterate the ResultSet like a common Iterator .
Each row column returned by SELECT will be represented how a map, using correspondent getter. For example, we will call getString() method when value of column is a varchar, getDate() when is a date and etc.
The complete code will be like this:
//Calling Oracle procedure CallableStatement cs = conn.prepareCall(""); //Defining type of return cs.registerOutParameter("o_cursor", OracleTypes.CURSOR); cs.setLong("i_id", id); cs.execute();//Running the call //Retrieving the cursor as ResultSet ResultSet rs = (ResultSet)cs.getObject("o_cursor"); //Iterating the returned rows while(rs.next()) < //Getting column values System.out.println("ID: " + rs.getLong("car_id")); System.out.println("Manufacturer: " + rs.getString("company")); System.out.println("Model: " + rs.getString("model")); System.out.println("Color: " + rs.getString("color")); System.out.println("HP: " + rs.getString("hp")); System.out.println("Price: " + rs.getFloat("price")); >
In the end you will get any value returned in a SELECT clause.