Showing posts with label CoreJava Code. Show all posts
Showing posts with label CoreJava Code. Show all posts

Wednesday, March 7, 2012

JDBC with oracle Example

package jdbc;

import java.sql.Timestamp;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class JdbcSample {

    static {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            System.out.println("Driver Loaded");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        Connection con = null;
        try {
            con = DriverManager.getConnection(
                    "jdbc:oracle:thin:@localhost:1521:sample", "test",
                    "test");
            System.out.println("Connection created");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return con;
    }

    public static void main(String[] args) throws Exception {
        System.out.println("Employee Database");
        System.out
                .println(" 0-Create Table\n 1-Insert\n 2-Find\n 3-Update\n 4-View\n 5-Delete");
        Scanner s = new Scanner(System.in);
        int input = s.nextInt();
        switch (input) {
        case 0:
            create();
            break;
        case 1:
            insert();
            break;
        case 2:
            find();
            break;
        case 3:
            update();
            break;
        case 4:
            view();
            break;
        case 5:
            delete();
        case 6:
            break;

        }
    }

//create table
    public static void create() {
        PreparedStatement ps = null;
        Connection con = null;
        try {

            final String createsql = ("create table Employee(id number(10),name varchar2(200),salary number(8,2),doj timestamp)");
            con = getConnection();
            ps = con.prepareStatement(createsql);
            ps.executeUpdate();
            System.out.println("Table created");
        } catch (SQLException e) {
            System.out.println("Error in creating tabls" + e);
        } finally {
            try {
                if (ps != null)
                    ps.close();
                if (con != null)
                    con.close();
                System.out.println("Connection closed");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

//Insert record
    public static void insert() {
        PreparedStatement ps = null;
        Connection con = null;
        int rs;
        try {
            Scanner s = new Scanner(System.in);
            System.out.println("Enter id:");
            int id = s.nextInt();
            System.out.println("Enter Employeename:");
            String employeename = s.next();
            System.out.println("Enter Salary:");
            double salary = s.nextDouble();

            // Long d=System.currentTimeMillis();
            // Date sqlDate = new java.sql.Date(d);
            java.sql.Timestamp sqlDate = new java.sql.Timestamp(
                    new java.util.Date().getTime());

            final String insertsql = ("Insert into Employee values(?,?,?,?)");
            con = getConnection();
            ps = con.prepareStatement(insertsql);
            ps.setInt(1, id);
            ps.setString(2, employeename);
            ps.setDouble(3, salary);
            // ps.setDate(4,sqlDate);
            ps.setTimestamp(4, sqlDate);
            rs = ps.executeUpdate();
            System.out.println(rs + " Record Inserted");
        } catch (SQLException e) {
            System.out.println("Error in inserting" + e);
        } finally {
            try {
                if (ps != null)
                    ps.close();
                if (con != null)
                    con.close();
                System.out.println("Connection closed");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

//Search Records
    public static void find() {
        PreparedStatement ps = null;
        Connection con = null;
        ResultSet rs = null;
        int count = 0;
        try {
            Scanner s = new Scanner(System.in);
            System.out.println("Enter id to find:");
            int id = s.nextInt();

            final String findsql = ("select * from Employee where id=?");
            con = getConnection();
            ps = con.prepareStatement(findsql);
            ps.setInt(1, id);
            rs = ps.executeQuery();

            while (rs.next()) {
                count = count + 1;
                String name = rs.getString("name");
                double salary = rs.getDouble("salary");
                // Date date=rs.getDate("doj");
                Timestamp date = rs.getTimestamp("doj");
                System.out.println("Employee Name:" + name + "\nSalary:"
                        + salary + "\nDate:" + date);
            }
            System.out.println(count + " Record found");

        } catch (SQLException e) {
            System.out.println("Error in finding" + e);
        } finally {
            try {
                if (ps != null)
                    ps.close();
                if (con != null)
                    con.close();
                System.out.println("Connection closed");
                if (rs != null)
                    rs.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

//Update Records
    public static void update() {
        PreparedStatement ps = null;
        Connection con = null;
        int rs;
        try {
            Scanner s = new Scanner(System.in);
            System.out.println("Enter id:");
            int id = s.nextInt();
            System.out.println("Enter Employeename:");
            String employeename = s.next();
            System.out.println("Enter Salary:");
            double salary = s.nextDouble();

            // Long d=System.currentTimeMillis();
            // Date sqlDate = new java.sql.Date(d);
            Timestamp sqlDate = new java.sql.Timestamp(
                    new java.util.Date().getTime());
            final String updatesql = ("Update Employee set name=?,salary=?,doj=? where id=?");
            con = getConnection();
            ps = con.prepareStatement(updatesql);

            ps.setString(1, employeename);
            ps.setDouble(2, salary);
            // ps.setDate(3,sqlDate);
            ps.setTimestamp(3, sqlDate);
            ps.setInt(4, id);
            rs = ps.executeUpdate();
            System.out.println(rs + " Record Updated");
        } catch (SQLException e) {
            System.out.println("Error in Updating" + e);
        } finally {
            try {
                if (ps != null)
                    ps.close();
                if (con != null)
                    con.close();
                System.out.println("Connection closed");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

//View records
    public static void view() {
        int count = 0;
        PreparedStatement ps = null;
        Connection con = null;
        ResultSet rs = null;
        try {
            final String viewsql = ("select * from Employee order by id,name");
            con = getConnection();
            ps = con.prepareStatement(viewsql);

            rs = ps.executeQuery();

            while (rs.next()) {
                count = count + 1;
                int id = rs.getInt("id");
                String name = rs.getString("name");
                double salary = rs.getDouble("salary");
                Timestamp date = rs.getTimestamp("doj");
                System.out.println(count + " Records ");
                System.out.println("ID:" + id + "\nEmployee Name:" + name
                        + "\nSalary:" + salary + "\nDate:" + date);
                System.out.println();
            }
            System.out.println(count + " Records Displayed");

        } catch (SQLException e) {
            System.out.println("Error in finding value" + e);
        } finally {
            try {
                if (ps != null)
                    ps.close();
                if (con != null)
                    con.close();
                System.out.println("Connection closed");
                if (rs != null)
                    rs.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

//Delete Records
    public static void delete() {
        PreparedStatement ps = null;
        Connection con = null;
        int rs;
        try {
            Scanner s = new Scanner(System.in);
            System.out.println("Enter id:");
            int id = s.nextInt();
            final String deletesql = ("delete from Employee where id=?");
            con = getConnection();
            ps = con.prepareStatement(deletesql);
            ps.setInt(1, id);
            rs = ps.executeUpdate();
            System.out.println(rs + "records deleted");
        } catch (SQLException e) {
            System.out.println("Error in Deleting" + e);
        } finally {
            try {
                if (ps != null)
                    ps.close();
                if (con != null)
                    con.close();
                System.out.println("Connection closed");

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

}

Note: For this we need a ojdbc14.jar file.

Wednesday, February 1, 2012

CharArrayReader


//Usage of CharArrayReader (It uses Character Array as a source)


import java.io.*;
public class CharArrayReaderDemo
{
public static void main(String args[]) throws IOException
{
String tmp = "abcdefghijklmnopqrstuvwxyz";
int length = tmp.length();
char c[] = new char[length];
tmp.getChars(0, length, c, 0);
CharArrayReader input1 = new CharArrayReader(c);
CharArrayReader input2 = new CharArrayReader(c, 0, 5);
int i;
System.out.println("input1 is:");
while((i = input1.read()) != -1)
{
System.out.print((char)i);
}
System.out.println();
System.out.println("input2 is:");
while((i = input2.read()) != -1)
{
System.out.print((char)i);
}
System.out.println();
}
}

Output:



input1 is:
abcdefghijklmnopqrstuvwxyz
input2 is:
abcde

Transfering the content of CharArrayWriter to FileWriter


// Usage of CharArrayWriter (It uses character array as a destination)


import java.io.*;
class CharArrayWriterDemo
{
public static void main(String args[]) throws IOException
{
CharArrayWriter f = new CharArrayWriter();
String s = "Welcome to CharArrayWriter";
char buf[] = new char[s.length()];
s.getChars(0, s.length(), buf, 0);
f.write(buf);

//f.reset();

System.out.println("Buffer as a string");
System.out.println(f.toString());

System.out.println("Into array");
char c[] = f.toCharArray();
for (int i=0; i<c.length; i++)
{
System.out.print(c[i]);
}

System.out.println("\nTo a FileWriter()");
FileWriter f2 = new FileWriter("test.txt");
f.writeTo(f2);
f2.close();

System.out.println("Doing a reset");
f.reset();

for (int i=0; i<3; i++)
f.write('X');
System.out.println(f.toString());
}
}

Output:



Buffer as a string
Welcome to CharArrayWriter
Into array
Welcome to CharArrayWriter
To a FileWriter()
==>here text.txt file is created.
Doing a reset
XXX


Reading a text from existing file in Character Stream


//Uasage of FileReader

import java.io.*;
class FileReaderDemo
{
public static void main(String args[]) throws Exception
{
FileReader fr = new FileReader("file3.txt");
BufferedReader br = new BufferedReader(fr);
String s;
while((s = br.readLine()) != null)
{
System.out.println(s);
}
fr.close();
}
}

Output:


Welcome to the FileWriter Demo
 Thanks for visiting
 visit again.

Creating .txt file and writing text to it in Character Stream

// Usage of FileWriter (Unicode format)

import java.io.*;
class FileWriterDemo
{
public static void main(String args[]) throws Exception
{
String source = "Welcome to the FileWriter Demo\n" + " Thanks for visiting\n" + " visit again.";
char buffer[] = new char[source.length()];
source.getChars(0, source.length(), buffer, 0);

FileWriter f0 = new FileWriter("file2.txt"); //stores the odd characters in file2.txt
for (int i=0; i < buffer.length; i += 2)
{
f0.write(buffer[i]);
}
f0.close();

FileWriter f1 = new FileWriter("file3.txt"); //stores all characters in file3.txt
f1.write(buffer);
f1.close();

FileWriter f2 = new FileWriter("file4.txt"); //stores the specifies index characters in file4.txt
f2.write(buffer,0,5); //stores 0 to 4th index character
f2.close();
}
}

Output:

Creates a three files file2.txt, file3.txt, file4.txt in the current folder path

Write primitive data to the file and retrive it (Data IO Stream )


Note: DataOutputStream and DataInputStream enable to read primitive data to or from a stream


import java.io.FileOutputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.DataInputStream;
import java.io.IOException;
public class DataIOStream
{
public static void main(String args[]) throws IOException
{
FileOutputStream fout=new FileOutputStream("Data.txt");
DataOutputStream out=new DataOutputStream(fout);

out.writeDouble(10.2);
out.writeInt(1000);
out.writeBoolean(true);

out.close();

FileInputStream fin=new FileInputStream("Data.txt");
DataInputStream in= new DataInputStream(fin);

double d=in.readDouble();
int i=in.readInt();
boolean b=in.readBoolean();

System.out.println("Double Values: " + d + "Integer Values: " + i + "Boolean Values: " + b);

in.close();
}
}

output:
Double Values: 10.2Integer Values: 1000Boolean Values: true

ByteArrayInputStream

ByteArrayInputStream:


import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.ByteArrayInputStream;
public class ByteArrayInputStreamDemo
{
public static void main(String args[])throws IOException
{
int size;
String s1="";
int c;
InputStream f1=new FileInputStream("file1.txt"); //reads text from existing file
System.out.println("Total size:" + (size=f1.available()));
for(int i=0;i<size;i++)
{
s1=s1+(char)f1.read();
}
System.out.println("S1:" + s1);

byte b[]=s1.getBytes();
ByteArrayInputStream input1=new ByteArrayInputStream(b);
ByteArrayInputStream input2=new ByteArrayInputStream(b,0,5);

//printing the input1 values 2 times(one in lowercase and another in uppercase)

for(int i=0;i<2;i++)
{
for(int j=0;j<b.length;j++)
while((c=input1.read())!=-1)
if(i==0)
System.out.print((char)c);
else
System.out.print(Character.toUpperCase((char)c));
input1.reset();
}

//printing the input2 values

for(int k=0;k<b.length;k++)
while((c=input2.read())!=-1)
System.out.print((char)c);
f1.close();
}
}

output:

Total size:34
S1:Hello Welcome to File Handling Bye
Hello Welcome to File Handling ByeHELLO WELCOME TO FILE HANDLING BYEHello

Transferring the content of ByteArrayOutputStream to FileOutputStream file

//ByteArrayOutputStream to FileOutputStream

import java.io.*;
class ByteArrayOutputStreamDemo
{
public static void main(String args[]) throws IOException
{
ByteArrayOutputStream f = new ByteArrayOutputStream();
String s = "This should end up in the array";
byte buf[] = s.getBytes();
f.write(buf);

System.out.println("Buffer as a string");
System.out.println(f.toString());

System.out.println("Into array");
byte b[] = f.toByteArray();

for (int i=0; i<b.length; i++)
{
System.out.print((char) b[i]);
}

System.out.println("\nTo an OutputStream()");
OutputStream f2 = new FileOutputStream("test.txt");
f.writeTo(f2);
f2.close();
System.out.println("Doing a reset");
f.reset();
for (int i=0; i<3; i++)
f.write('X');
System.out.println(f.toString());
}
}

Reading text from existing file in byteStream

//Usage of FileInputStream Class

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
public class FileInputStreamDemo
{
public static void main(String args[])throws IOException
{
int size;
String s1="";
InputStream f1=new FileInputStream("file1.txt"); //reads text as a byte from the existing file in the current path
System.out.println("Total size:" + (size=f1.available()));
for(int i=0;i<size;i++)
{
//if(i==10)
//f1.skip(4); //It skips the 4 characters from 10th position
System.out.print((char)f1.read());
}
f1.close();
}
}

Output:

Total size:34
Hello Welcome to File Handling Bye

Creating a .txt file and writing text to it in byteStream

Usage of FileOutputStream Class:


import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.IOException;
public class FileOutputStreamDemo
{
public static void main(String args[])throws IOException
{
String source="Hello Welcome to File Handling Bye";
byte buf[]=source.getBytes();

OutputStream f1=new FileOutputStream("f:/file1.txt");
f1.write(buf);
f1.close();
}
}


output:

Creates a file1.txt file in a specified path and writes a String to it.

Displays all files names with path within the specified path

Usage of ListFiles:

import java.io.File;
import java.util.*;
class FileDemo1
{
public static void main(String args[])
{
List<File> l=new ArrayList<File>();
File f=new File("F:/DO IT/Home Practice/Files");
f.mkdirs(); //If directory does not exist, will make a directory and path specified
if(f.isDirectory())
{
//String s[]=f1.list(only);     //list will return the file list as an array of String
File files[]=f.listFiles(); //listFiles will return the file list as an array of File object instead of Strings
for(File fil:files)
l.add(fil);
}
Iterator<File> i=l.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}

output:

F:\DO IT\Home Practice\Files>java FileDemo1
F:\DO IT\Home Practice\Files\ByteArrayInputStreamDemo.class
F:\DO IT\Home Practice\Files\ByteArrayInputStreamDemo.java
F:\DO IT\Home Practice\Files\ByteArrayOutputStreamDemo.class
F:\DO IT\Home Practice\Files\ByteArrayOutputStreamDemo.java


Displays the All files names with specified extention within a specified path

Using FilternameFilter


 OnlyExt.java (Common)

import java.io.*;
public class OnlyExt implements FilenameFilter
{
String ext;
OnlyExt(String ext)
{
this.ext=ext;
}
public boolean accept(File dir, String name)
{
return name.endsWith(ext); //return name.startsWith(ext);
}
}

DirListOnly .java


import java.io.*;
import java.util.*;
class DirListOnly
{
public static void main(String args[])
{
String dirname="F:/DO IT/Home Practice/Files";
String extention;
System.out.println("Enter the Extention of a files:");
Scanner sc=new Scanner(System.in);
extention=sc.next();
File f1=new File(dirname);
FilenameFilter only=new OnlyExt(extention);
String s[]=f1.list(only);
if(s.length!=0)
{
for(String s1:s)
System.out.println(s1);
}
else
{
System.out.println("No Files Found");
}
}
}

output:
javac OnlyExt.java
javac DirListOnly.java
java DirListOnly


Enter the Extention of a files:
class
ByteArrayInputStreamDemo.class
ByteArrayOutputStreamDemo.class
DirListOnly.class
FileDemo1.class
FileInputStreamDemo.class
FileOutputStreamDemo.class
OnlyExt.class



Displays all directories and file names in the specified path


//Usage of File class and isDirectory and list method

import java.io.*;
class DirList
{
public static void main(String args[])
{
String dirname="F:/DO IT/Home Practice";
File f1=new File(dirname);
if(f1.isDirectory())
{
System.out.println("Directory of" + dirname);
String s[]=f1.list();
for(int i=0;i<s.length;i++)
{
File f=new File(dirname + "/" + s[i]);
if(f.isDirectory())
{
System.out.println(s[i]  + "is a directory");
}
else
{
System.out.println(s[i] + "is a file");
}
}
}
else
{
System.out.println(dirname + "is not a directory");
}
}
}

output:
Directory ofF:/DO IT/Home Practice
Collectionsis a directory
Dateis a directory
FileIOis a directory
Filesis a directory
Packageis a directory
String Handlingis a directory
StringRev.classis a file
StringRev.javais a file

Monday, January 16, 2012

ArrayDeque - used like a Stack

import java.util.*;
class ArrayDequeDemo
{
public static void main(String args[])
{
//create ArrayDeque
ArrayDeque<String> adq=new ArrayDeque<String>();

//using ArrayDeque like stack.
adq.push("A");
adq.push("B");
adq.push("D");
adq.push("E");
adq.push("C");
adq.push("F");
System.out.println(adq);

//Popping the elements from ArrayDeque
System.out.println("Popping the stack");
while(adq.peek()!=null)  //  returns null if this deque is empty.
{
System.out.println(adq.pop() +"- popped ");
}
System.out.println(adq);
}

}

Output:
[F, C, E, D, B, A]
Popping the stack
F- popped
C- popped
E- popped
D- popped
B- popped
A- popped
[]

Note:

  • ArrayDeque implements Deque

TreeSet


import java.util.*;
class TreeSetDemo
{
public static void main(String args[])
{
//create TreeSet
TreeSet<String> hs=new TreeSet<String>();
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);

//Iterator to display elements
                System.out.println("Displaying contents of hs using for each: ");
Iterator itr=hs.iterator();
while(itr.hasNext())
{
Object element=itr.next();
System.out.print(element + "-");
}
System.out.println();

//For each, alternative to iterator
System.out.println("Displaying contents of hs using for each: ");
for(String s:hs)
System.out.print(s + " ");
System.out.println();

//--------------------------------------------------------
//adding a to z in TreeSet
System.out.println();
LinkedHashSet<Character> h=new LinkedHashSet<Character>();
for(int i=97;i<122;i++)
h.add((char)i);
h.add('b');
System.out.println(h);

//Iterator to display elements
                System.out.println("Displaying contents of hs using for each: ");
Iterator itr1=h.iterator();
while(itr1.hasNext())
{
Object element=itr1.next();
System.out.print(element + "-");
}
System.out.println();

//For each, alternative to iterator
System.out.println("Displaying contents of h using for each: ");
for(Character s1:h)
System.out.print(s1 + " ");
System.out.println();

}
}


Output:


[A, B, C, D, E, F]
Displaying contents of hs using Iterator:
A-B-C-D-E-F-
Displaying contents of hs using for each:
A B C D E F

[a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y]
Displaying contents of h using Iterator:
a-b-c-d-e-f-g-h-i-j-k-l-m-n-o-p-q-r-s-t-u-v-w-x-y-
Displaying contents of h using for each:
a b c d e f g h i j k l m n o p q r s t u v w x y



Note:
  • LinkedHashSet guarantee the elements in sorted, ascending order.
  • In LinkedHashSet ListIterator cannot be used.
  • LinkedHashSet implements NavigableSet interface.


LinkedHashSet

import java.util.*;
class LinkedHashSetDemo
{
public static void main(String args[])
{
//create HashSet
LinkedHashSet<String> hs=new LinkedHashSet<String>();
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);

//Iterator to display elements
System.out.println("Displaying contents of hs using Iterator: ");
Iterator itr=hs.iterator();
while(itr.hasNext())
{
Object element=itr.next();
System.out.print(element + "-");
}
System.out.println();

//For each, alternative to iterator
System.out.println("Displaying contents of hs using for each: ");
for(String s:hs)
System.out.print(s + " ");
System.out.println();

//--------------------------------------------------------
//adding a to z in HashSet
System.out.println();
LinkedHashSet<Character> h=new LinkedHashSet<Character>();
for(int i=97;i<122;i++)
h.add((char)i);
h.add('b');
System.out.println(h);

//Iterator to display elements
System.out.println("Displaying contents of h using Iterator: ");
Iterator itr1=h.iterator();
while(itr1.hasNext())
{
Object element=itr1.next();
System.out.print(element + "-");
}
System.out.println();

//For each, alternative to iterator
System.out.println("Displaying contents of h using for each: ");
for(Character s1:h)
System.out.print(s1 + " ");
System.out.println();
}
}


Output:
[B, A, D, E, C, F]
Displaying contents of hs using Iterator:
B-A-D-E-C-F-
Displaying contents of hs using for each:
B A D E C F

[a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y]
Displaying contents of h using Iterator:
a-b-c-d-e-f-g-h-i-j-k-l-m-n-o-p-q-r-s-t-u-v-w-x-y-
Displaying contents of h using for each:
a b c d e f g h i j k l m n o p q r s t u v w x y


Note:
  • LinkedHashSet guarantee the order of its elements in which they were inserted.
  • In LinkedHashSet ListIterator cannot be used.
  • LinkedHashSet implements Set interface.

HashSet

import java.util.*;
class HashSetDemo
{
public static void main(String args[])
{
//create HashSet
HashSet<String> hs=new HashSet<String>();
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);

//Iterator to display elements
System.out.print("Displaying contents of hs using Iterator: ");
Iterator itr=hs.iterator();
while(itr.hasNext())
{
Object element=itr.next();
System.out.print(element + " ");
}
System.out.println();

//For each, alternative to iterator
System.out.print("Displaying contents of hs using for each: ");
for(String s:hs)
System.out.print(s + " ");
System.out.println();
//--------------------------------------------------------
//adding a to z in HashSet
System.out.println();
HashSet<Character> h=new HashSet<Character>();
for(int i=97;i<122;i++)
h.add((char)i);
h.add('b');
System.out.println(h);

//Iterator to display elements
System.out.println("Displaying contents of h using Iterator: ");
Iterator itr1=h.iterator();
while(itr1.hasNext())
{
Object element=itr1.next();
System.out.print(element + "-");
}
System.out.println();

//For each, alternative to iterator
System.out.println("Displaying contents of h using for each: ");
for(Character s1:h)
System.out.print(s1 + " ");
System.out.println();

}
}

Output:
[D, E, F, A, B, C]
Displaying contents of hs using Iterator: D E F A B C
Displaying contents of hs using for each: D E F A B C

[f, g, d, e, b, c, a, n, o, l, m, j, k, h, i, w, v, u, t, s, r, q, p, y, x]
Displaying contents of h using Iterator:
f-g-d-e-b-c-a-n-o-l-m-j-k-h-i-w-v-u-t-s-r-q-p-y-x-
Displaying contents of h using for each:
f g d e b c a n o l m j k h i w v u t s r q p y x

Note:
  • HashSet does not guarantee the order of its elements
  • In HashSet ListIterator cannot be used.
  • HashSet implements Set Interface.



Linked List

import java.util.*;
class LinkedListDemo
{
public static void main(String args[])
{
// create a linked list
LinkedList<String> ll = new LinkedList<String>();

// add elements to the linked list
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
System.out.println("Original contents of ll: " + ll);

//adding first and last element in linkedlist
ll.addLast("Z");
ll.addFirst("A");
ll.add(1, "A2");
System.out.println("contents of ll after adding first and last: " + 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);

//Iterator to display elements
System.out.print("Displaying contents of ll using Iterator: ");
Iterator itr = ll.iterator();
while(itr.hasNext())
{
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();

//For each, alternative to iterator
System.out.print("Displaying contents of ll using for each: ");
for(String s:ll)
{
System.out.print(s + " ");
}
System.out.println();

// modify objects being iterated
ListIterator litr = ll.listIterator();
while(litr.hasNext())
{
Object element = litr.next();
litr.set(element + "+");
}

System.out.print("Modified contents of ll: ");
itr = ll.iterator();
while(itr.hasNext())
{
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();

// now, display the list backwards
System.out.print("Modified list backwards: ");
while(litr.hasPrevious())
{
Object element = litr.previous();
System.out.print(element + " ");
}
System.out.println();
}
}

Output:
Original contents of ll: [F, B, D, E, C]
contents of ll after adding first and last: [A, A2, F, B, D, E, C, Z]
Contents of ll after deletion: [A, A2, D, E, C, Z]
ll after deleting first and last: [A2, D, E, C]
ll after change: [A2, D, E Changed, C]
Displaying contents of ll using Iterator: A2 D E Changed C
Displaying contents of ll using for each: A2 D E Changed C
Modified contents of ll: A2+ D+ E Changed+ C+
Modified list backwards: C+ E Changed+ D+ A2+

Note:
LinkedList implements List, Deque and Queue.

Converting an ArrayList into an array.


//Obtaining an Array from an ArrayList

import java.util.*;
class ArrayListToArray
{
public static void main(String args[])
{
// Create an array list
ArrayList<Integer> al = new ArrayList<Integer>();

// Add elements to the array list
al.add(new Integer(1));
al.add(new Integer(2));
al.add(new Integer(3));
al.add(new Integer(4));
System.out.println("Contents of al: " + al);

// get array
Object ia[] = al.toArray();
int sum = 0;

//Display using array
System.out.println("Display using array");
for(int i=0;i<ia.length;i++)
{
System.out.println(ia[i]);
}

// sum the array
for(int i=0; i<ia.length; i++)
sum += ((Integer) ia[i]).intValue();
System.out.println("Sum is: " + sum);
}
}

Output:

Contents of al: [1, 2, 3, 4]
Display using array
1
2
3
4
Sum is: 10


Note:
Reasons to convert ArrayList to Array:
  • To obtain faster processing times for certain operations.
  • To pass an array to a method that is not overloaded to accept a collection.
  • To integrate collection-based code with legacy code that does not understand collections.

Array List


import java.util.*;
class ArrayListDemo
{
public static void main(String args[])
{
// create an array list
ArrayList<String> al = new ArrayList<String>();
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());
System.out.println("Contents of al: " + al);

//Iterator to display elements
System.out.print("Displaying contents of al using Iterator: ");
Iterator itr = al.iterator();
while(itr.hasNext())
{
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();

//For each, alternative to iterator
System.out.print("Displaying contents of al using for each: ");
for(String s:al)
{
System.out.print(s + " ");
}
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 + " ");
}
System.out.println();

// now, display the list backwards
System.out.print("Modified list backwards: ");
while(litr.hasPrevious())
{
Object element = litr.previous();
System.out.print(element + " ");
}
System.out.println();


}
}


Output:

Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]
Displaying contents of al using Iterator: C A2 E B D
Displaying contents of al using for each: C A2 E B D
Modified contents of al: C+ A2+ E+ B+ D+
Modified list backwards: D+ B+ E+ A2+ C+


Note:
  • ArrayList implements only List interface.