0% found this document useful (0 votes)
6 views75 pages

Java Package Management and I/O Basics

This document provides an overview of Java packages, including how to define, create, and access them, as well as the types of packages and the concept of CLASSPATH. It also covers access control for class members within packages and introduces Java I/O programming, detailing various input and output stream classes and their methods. Examples illustrate the use of packages, class visibility, and I/O operations in Java.

Uploaded by

govindasairam369
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views75 pages

Java Package Management and I/O Basics

This document provides an overview of Java packages, including how to define, create, and access them, as well as the types of packages and the concept of CLASSPATH. It also covers access control for class members within packages and introduces Java I/O programming, detailing various input and output stream classes and their methods. Examples illustrate the use of packages, class visibility, and I/O operations in Java.

Uploaded by

govindasairam369
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT-3

 Defining Package
 Creating and Accessing a Package
 Types of packages
 Understanding CLASSPATH
 importing packages
Packages
Java provides a mechanism for partitioning the class name space into more
manageable chunks. This mechanism is the package.

The package is both a naming and a visibility control mechanism.

A package represents a directory that contains related group of classes and


interfaces.

You can define classes inside a package that are not accessible by code outside that
package.

You can also define class members that are only exposed to other members of the
same package.
Pre-defined packages
1. [Link] 11. [Link]
2. [Link] 12. [Link]
3. [Link] 13. [Link]
4. [Link] [Link]
5. [Link] [Link]
6. [Link]
7. [Link]
8. [Link]
9. [Link]
10. [Link]
Defining a Packages
To create a package is quite easy: simply include a package command as the first
statement in a Java source file.

Any classes declared within that file will belong to the specified package.

The package statement defines a name space in which classes are stored.
If you omit the package statement, the class names are put into the default
package, which has no name.

This is the general form of the package statement:


Syntax: package pkg;

Example: package MyPackage;

Java uses file system directories to store packages.


More than one file can include the same package statement.

You can create a hierarchy of packages.

To do so, simply separate each package name from the one above it by use of a
period.

The general form of a multileveled package statement is shown here:


package pkg1[.pkg2[.pkg3]];

A package hierarchy must be reflected in the file system of your Java development
system.

For example, a package declared as package [Link]; needs to be stored in


java\awt\image on your Windows.
Finding Packages and CLASSPATH
How does the Java run-time system know where to look for packages that you
create?

The answer has two parts:


First, by default, the Java run-time system uses the current working directory as its
starting point. Thus, if your package is in the current directory, or a subdirectory of
the current directory, it will be found.

Second, you can specify a directory path or paths by setting the CLASSPATH
environmental variable.
For example, consider the following package specification.
package MyPack;
In order for a program to find MyPack, one of two things must be true.
Either the program is executed from a directory immediately above MyPack, or
CLASSPATH must be set to include the path to MyPack.
// A simple package //[Link]
package MyPack; class AccountBalance {
class Balance { public static void main(String args[]) {
Balance current[] = new Balance[3];
String name; current[0] = new Balance("K. J. Fielding", 123.23);
double bal; current[1] = new Balance("Will Tell", 157.02);
Balance(String n, double b){ current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++)
name = n; current[i].show();
bal = b; }
} }

void show() {
if(bal<0)
[Link]("--> "); //To compile
javac [Link]
[Link](name + ": $" + bal);
} //To run
} java [Link]

//java AccountBalance invalid


Access Control of packages

Java addresses four categories of visibility for class members:

➢ Subclasses in the same package.

➢ Non-subclasses in the same package.

➢ Subclasses in different packages.

➢ Classes that are neither in the same package nor subclasses.

A class has only two possible access levels: default and public.
Class Member Access
//[Link]
package pack1;
public class VarProtection {
int n = 1;
private int pri = 2;
protected int pro = 3;
public int pub = 4;
public VarProtection() {
[Link]("Individual class constructor");
[Link]("default value is: " + n);
[Link]("private value is: " + pri);
[Link]("protected value is: " + pro);
[Link]("public value is: " + pub);
} To Compile:
} d:\>javac –d . [Link]
//SameSub .java:
package pack1;
class SameSub extends VarProtection{
SameSub(){
[Link]("subclass constructor");
[Link]("default value is: " + n);
// [Link]("private value is: " + pri);
[Link]("protected value is: " + pro);
[Link]("public value is: " + pub);
}
}

To Compile:
d:\>javac –d . [Link]
// [Link]
package pack1;
class SameDiff{
SameDiff(){
VarProtection v1 = new VarProtection();
[Link]("Delegationclass constructor");
[Link]("default value is: " +v1. n);
// [Link]("private value is: " +v1. pri);
[Link]("protected value is: " +v1. pro);
[Link]("public value is: " + [Link]);
}
}

To Compile:
d:\>javac –d . [Link]
//[Link]
package pack2;
import pack1.*;
class OtherSub extends VarProtection{
OtherSub(){
[Link]("Different Package subclass constructor");
//[Link]("default value is: " + n);
// [Link]("private value is: " + pri);
[Link]("protected value is: " + pro);
[Link]("public value is: " + pub);
}
}

To Compile:
d:\>javac –d . [Link]
// [Link]
package pack2;
import pack1.*;
class OtherDiff{
OtherDiff(){
VarProtection v2=new VarProtection();
[Link]("Different Package non-subclass constructor");
// [Link]("default value is: " +v2. n);
// [Link]("private value is: " + [Link]);
// [Link]("protected value is: " + [Link]);
[Link]("public value is: " + [Link]);
}
}

To Compile:
d:\>javac –d . [Link]
// Demo package p1. To Compile:
d:\>javac –d . [Link]
package pack1;
To Run:
Import pack1.*; d:\>java [Link]
class MainTest{
public static void main(String args[]){
VarProtection v=new VarProtection();
SameDiff s2=new SameDiff();
SameSub s1=new SameSub();
}
package pack2;
}
import pack1.*;
class OtherMainTest{
public static void main(String args[]){
OtherSub os=new OtherSub();
To Compile: OtherDiff od=new OtherDiff();
d:\>javac –d . [Link] }
To Run:
d:\>java [Link] }
Importing user-defined Packages

There are no core Java classes in the unnamed default package; all of the standard
classes are stored in some named package.

Java includes the import statement to bring certain classes, or entire packages,
into visibility.

Once imported, a class can be referred to directly, using only its name.

In a Java source file, import statements occur immediately following the


package statement (if it exists) and before any class definitions.

This is the general form of the import statement:


import pkg1[.pkg2].(classname|*);
Here, pkg1 is the name of a top-level package, and pkg2 is the name of a
subordinate package inside the outer package separated by a dot (.).

There is no practical limit on the depth of a package hierarchy, except that


imposed by the file system.

Finally, you specify either an explicit classname or a star (*), which indicates that
the Java compiler should import the entire package.

This code fragment shows both forms in use:


import [Link];
import [Link].*;
All of the standard Java classes included with Java are stored in a package called
java.

The basic language functions are stored in a package inside of the java package
called [Link].

Normally, you have to import every package or class that you want to use, but
[Link] is implicitly imported by the compiler for all programs.

This is equivalent to the following line being at the top of all of your programs:
import [Link].*;
When a package is imported, only those items within the package declared as public will
be available to non-subclasses in the importing code. For example, if you want the
Balance class of the package MyPack shown earlier to be available as a stand-alone
class for general use outside of MyPack, then you will need to declare it as public and
put it into its own file, as shown here:
package MyPack;
public class Balance {
String name;
double bal;
public Balance(String n, double b) {
name = n;
bal = b;
}
public void show() {
if(bal<0)
[Link]("--> ");
[Link](name + ": $" + bal);
}
}
import MyPack.*;
class TestBalance {
public static void main(String args[]) {
/* Because Balance is public, you may use Balance
class and call its constructor. */
Balance test = new Balance("J. J. Jaspers", 99.88);
[Link](); // you may also call show()
}
}

As an experiment, remove the public specifier from the Balance class and then
try compiling TestBalance. As explained, errors will result.
Introduction to I/O Programming:
Introduction to I/O Programming:

➢DataInputStream

➢DataOutputStream

➢FileInputStream

➢FileOutputStream

➢BufferedReader
Introduction
➢Input refers to reading data from some external source into a
running program.
➢Output refers to writing data from a running program to some
external destination.
➢A file is a collection of data stored on a disk or CD or some
other storage medium.

➢Files and their data persist beyond the duration of the program.

➢A stream is an object that delivers information to and from


another object.

➢All I/O in Java is based on streams.


/O in Java is based on streams.
• A stream, in java, is an object that reads data from a
source(keyboard, mouse, memory, disk, network, or another
program.) or writes data to a source (screen, printer,
memory, disk, network, another program).
IO Streams:
➢There are two types of streams – input streams and output
streams.

➢ An input stream job is to read from the source

➢The output stream job is to write to the destination. That is, in


the program,

➢It is necessary to link the input stream object to the source and
the output stream object to the destination.

➢I/O streams are carriers of data from one place to another.


➢ss.
➢ The input stream carries data from the source and places it
temporarily in a variable (like int k or String str etc.) in the
process.

➢ The output stream takes the data from the variable and writes
to the destination.

➢ The variable works like a temporary buffer between input


stream and output stream.
An InputStream or Reader is linked to a source of data.
An OutputStream or Writer is linked to a destination of data.
Class Description
FileInputStream Provides methods for reading bytes from a file

FileOutputStream Provides methods for writing bytes to a file

DataInputStream Provides methods for reading Java's primitive data types

DataOutputStream Provides methods for writing Java's primitive data types

FileReader Provides methods for reading characters from a file

BufferedReader Provides buffering for character input streams


FileInputStream
• The FileInputStream class creates a Stream that can be used to
read bytes from a file.
• Its two most common constructors are shown below:

1. FileInputStream(String filepath)
2. FileInputStream(File fileObj)

• Here, filepath is the path of the file, and fileObj is a File object
that describes the file.
Methods in FileInputStream
Method Description
int read( ) Returns an integer representation of the next
available byte of input. –1 is returned when the
end of the file is encountered.

int available( ) Returns the number of bytes of input currently


available for reading.

void close( ) Closes the input source. Further read attempts will
generate an IOException.
FileOutputStream
• FileOutputStream creates a Stream that can be used to write
bytes to a file.
• Its commonly used constructors are shown below:

➢ FileOutputStream(String filePath)
➢ FileOutputStream(File fileObj)
➢ FileOutputStream(String filePath, boolean append)

• Here, filePath is the of a file, and fileObj is a File object that


describes the file. If append is true, the file is opened in
append mode.
Methods in FileOutputStream

Method Description
void write(int b) Writes a single byte to an output stream.

void close( ) Closes the output stream. Further write attempts


will generate an IOException.
Example:
import [Link].*;
public class FileInputOutputExample
{
public static void main(String[] args) throws Exception
{
FileInputStream is = new FileInputStream("[Link]");
FileOutputStream os = new FileOutputStream("[Link]");
int c;
while ((c = [Link]()) != -1)
{
[Link]((char) c);
[Link](c);
}
[Link]();
[Link]();
} }
DataOutputStream
• Java DataOutputStream class allows an application to write primitive Java data
types to the output stream in a machine-independent way.
• Java application generally uses the data output stream to write data that can
later be read by a data input stream.
• Constructor
– DataOutputStream(OutputStream out)

• Methods
– writeBoolean(boolean v)
– writeByte(int b)
– writeShort(int s)
– writeChar(int c)
– writeInt(int i)
– writeLong(long l)
– writeFloat(float f)
– writeDouble(double d)
DataInputStream
• Java DataInputStream class allows an application to read primitive data from the
input stream in a machine-independent way.
• Java application generally uses the data output stream to write data that can later
be read by a data input stream.
• Constructor
– DataInputStream(InputStream in)

• Methods
– boolean readBoolean(boolean v)
– byte readByte(int b)
– short readShort(int s)
– char readChar(int c)
– int readInt(int i)
– long readLong(long l)
– float readFloat(float f)
– double readDouble(double d)
Example
DataInputStream dis= new DataInputStream(
import [Link].*; new FileInputStream(“[Link]") ) ;
public class DataOutStreamDataInputStream
{ int a= [Link]();
public static void main(String[] args) throws float b = [Link]();
IOException long c = [Link]();
{ [Link]();
DataOutputStream dos= new
DataOutputStream( new
[Link](“a = " + a);
FileOutputStream("[Link]") );
[Link](“b = " + b);
[Link](“c = " + c);
[Link](123);
}
[Link](123.45F);
}
[Link](789);
[Link]();
FileReader

• The FileReader class creates a Reader that can be used to read


characters from a file.
• Its two most commonly used constructors are shown below:

– FileReader(String filePath)
– FileReader(File fileObj)
Example

import [Link].*;
public class FileReaderExample
{
public static void main(String[] args) throws Exception
{
FileReader fis = new FileReader ("[Link]");

int c;
while ((c = [Link]()) != -1)
{
[Link]( (char)c );
}
[Link]();
}
}
BufferedReader class
• Java BufferedReader class is used to read the text from a character-based
input stream. It can be used to read data line by line by readLine() method. It
makes the performance fast.

• It is a character based input stream class.


• It reads more characters than initially needed and store them in a buffer.
• So when the buffered reader's read() method is called, the data is read from
the buffer rather than from the file.
• When the buffer is empty, the buffered stream refills the buffer.
• It improves the performance of I/O
• One long disk access takes less time than many smaller ones.
• It reads large amount of data at a time into the buffer.
• BufferedReader Constructors
• It has two constructors
– BufferedReader( Reader inputstream )
– BufferedReader( Reader inputstream , int bufSize )
Ex: BufferedReader with a FileReader
import [Link].*;
public class BufferedReaderExample
{
public static void main(String[] args) throws Exception
{
FileReader fis = new FileReader ("[Link]");
BufferedReader br=new BufferedReader(fis);

int c;
while ((c = [Link]()) != -1)
{
[Link]( (char)c );

}
[Link](); } }
Example 2:
import [Link].*;
class BufferedReaderEx
{
public static void main(String args[]) throws IOException
{
InputStreamReader is=new InputStreamReader([Link]);//reading data
from console.
BufferedReader br=new BufferedReader(is);
String str=[Link]();
[Link]("Welcome to "+str);
}
}
output:
>java BufferedReaderEx
this is cseaiml
Welcome to this is cseaiml
Problems in Storing objects into an Array.
We can store a group of similar datatype objects into an array
and retrieve them again easily but there are some
disadvantages in this mechanism;
1. We cannot store different class objects into the same array.
Because an array can store only homogenous data elements.
2. Adding objects at the end of an array is easy, But, inserting
and deleting the elements in the middle of the array is
difficult.
3. Retrieving the elements from an array is easy but after
retrieving the elements, if we want to process them, then there
are no methods available to carryout this.
Due to this problems, programmer want a better mechanism to
store group of objects, the alternative is collection framework.
Collections Framework

➢Collections Framework is a hierarchy of interfaces and classes


that provide mechanism for managing groups of objects.
➢Collection framework is a class library to handle group of
objects. It is implemented in util package.
What is Collection?
Def: “Collection is a single entity which is representing multiple
objects.”
➢A collection is an object that can hold references to other
objects.
The collection holds references of other objects only, does not
store copy of the other objects
➢The classes and interfaces of the collections framework are
in [Link] package.
ck
Collections frame work contains the following

• Interfaces .

• Implementations -These are the classes of collection framework.

• Algorithms -These are the methods that perform useful


computations, such as searching and sorting, on objects that
implement collection interfaces.
Interfaces
Collection that Root interface for functions common
cannot contain to all types of collections
duplicates.
Collection Collection with functions for FIFO
and priority queues.

hSet List Queue

Collection with
Dequeue operations for Double
SortedSet ended queue.
Stores a sequence of elements and
allows duplicate elements.

Special Set that maintains


the ordering of elements.
Interface Type Implimentation classes

Set<T> HashSet<T>
LinkedHashSet<T>

List<T> Stack<T>
LinkedList<T>
ArrayList<T>
Vector<T>

Queue<T>
Interface Type
LinkedList<T>

Map<K,V> HashMap<K,V>
Hashtable<K,V>

47
Sets:
A set represents a group of elements arranged just like an array.
The set will grow dynamically when the elements are stored
into it. A set will not allow duplicate elements or values.
Lists:
Lists are like sets. They store group of elements. But Lists allow
duplicate values to be stored.
Queues:
A Queue arrangement of elements in FIFO order.
Maps:
Maps store elements in the form of key and value pairs. If the key
is provided then its corresponding value can be obtained. The
key should have unique values.

48
<<interface>>
<<interface>>
Queue<E>> Deque<E>
Interfaces and +add(E):boolean +add(E):boolean
their methods +remove(Object):boolean
+contains(Object):boolean
+remove(Object):boolean
+contains(Object):boolean
+size():int +size():int
+element():E
+element():E +remove():E
+remove():E +peek():E
+peek():E +poll():E
+poll():E +addFirst(Object): void
+addLast(Object):void
<<interface>> +getFirst(): E
List<E>t<E> +getLast():E
<c<<interface>>
+add(E):boolean +removeFirst():E
Collection<E>on<E> +removeLast():E():E
+remove(Object):boolean
+add(E):boolean +get(int):E
+remove(Object):boolean +indexOf(Object):int
+contains(Object):boolean +contains(Object):boolean <<interface>>
+size():int +size():int
etc… SortedSet<E> >>
etc…etc…
+add(E):boolean
+remove(Object):boolean
<<interface>> +contains(Object):boolean
Set<E> +size():int
+first():E
+add(E):boolean
+last():E
+remove(Object):boolean
+contains(Object):boolean +subSet(Object,Object) :
+size():int SortedSet
etc… etc…etc…
The Collection Interface

➢ The Collection interface is the foundation upon which the


collections framework is built.

➢ Collection is a generic interface that has this declaration:


interface Collection<E>

➢ Here E specifies the type of objects that the collection will


hold.
The methods defined by Collection

Method Description
boolean add(E obj ) Returns true if obj was added at end of the collection. Returns
false if obj is already a member of the collection. Collection does
not allow duplicates.

boolean remove(Object obj) Removes obj from the collection . Returns true if the element was
removed. Otherwise returns false.

void clear( ) Removes all elements from the collection.

boolean isEmpty() Returns true if the collection is empty. Otherwise, returns false.

int size() Returns the number of elements held in the collection


The List Interface
➢ The List interface extends Collection and 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.
➢ List interface is the child interface of Collection interface. It
inhibits a list type data structure in which we can store the
ordered collection of objects.
➢ List interface is implemented by the classes ArrayList,
LinkedList, Vector, and Stack.
➢ List is a generic interface that has this declaration:
Interface List<E>
The instantiation of List interface must follow as,

• List <data-type> list1= new ArrayList();


• List <data-type> list2 = new LinkedList();
• List <data-type> list3 = new Vector();
• List <data-type> list4 = new Stack();

53
The methods defined by List
Method Description
void add(E obj ) Inserts obj at the end of the list.

void add(int index, E obj) Inserts obj at the specified index . Any preexisting elements at or
beyond the point of insertion are shifted towards right.
E get(int index) Returns the object stored at the specified index.

int indexOf(Object obj) Returns the index of the first obj in the invoking list. If obj is not an
element of the list, –1 is returned.

int lastIndexOf(Object obj) Returns the index of the last obj in the invoking list. If obj is not an
element of the list, –1 is returned .
E remove(int index) Removes the element at position index t and returns the deleted
element. The indexes of subsequent elements are decremented by one.
The Set Interface
➢ The Set extends Collection and does not allow duplicate
elements.

➢ Set is implemented by HashSet, LinkedHashSet, and TreeSet.

➢ It represents the unordered set of elements which doesn't allow


us to store the duplicate items.

➢ 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.

➢ We can store at most one null value in Set.


The instantiation of Set interface must follow as,

1. Set<data-type> s1 = new HashSet<data-type>();


2. Set<data-type> s2 = new LinkedHashSet<data-type>();

3. Set<data-type> s3 = new TreeSet<data-type>();

SortedSet Interface
➢ SortedSet is the alternate of Set interface that provides a total
ordering on its elements.
➢ The elements of the SortedSet are arranged in the increasing
(ascending) order.
➢ The SortedSet provides the additional methods that inhibit the
natural ordering of the elements.
The SortedSet Interface

Method Description
Object first( ) Returns the first element in the invoking sorted set.

Object last( ) Returns the last element in the invoking sorted set.

SortedSet subSet(Object Returns a SortedSet that includes those elements


start, Object end) between start and end–1.
The queue interface
➢ The queue interface extends Collection and declares
the behavior of a queue, which is often first-in, first-
out list.
➢ Queue is a generic interface that has this declaration
interface Queue<E>

➢Classes like PriorityQueue, Deque, and


ArrayDeque which implements the Queue
interface.
Methods defined by a queue

Method description
E element() Returns the element at the head of the queue. The element is
not removed. It throws NoSuchElementException if the
queue is empty.
E remove() Removes the element at the head of the queue and returns that
element. It throws NoSuchElementException if the queue is
empty.
E peek() Returns the element at the head of the queue. The element is
not removed. It returns null if the queue is empty.

E poll() Removes the element at the head of the queue and returns that
element. It returns null if the queue is empty.
The deque interface
➢ It was added by Java SE 6.
➢ It extends queue and declares the behavior of a
double ended queue.
➢ Double ended queue can function as first-in, first-out
queues or as last-in, first-out stacks.
Methods defined by deque

Method description
void addFisrt(E obj) Adds obj to the head of the queue.

void addLast(E obj) Adds obj to the tail of the queue.

E getFirst() Returns the first element in the queue. The element is not
removed.
E getLast() Returns the last element in the queue. The element is not
removed.
E removeFirst() Returns and removes the first element.

E removeLast() Returns and removes the last element.

61
The Collection Classes
➢ Collection classes are classes that implement
collection interfaces .

➢ Some of the classes provide full implementations that


can be used to maintain group of objects.

➢ Others are abstract classes.


The ArrayList Class
➢ The ArrayList class implements the List interface.
➢ ArraylList is a generic class that has this declaration:
class ArrayList<E>
➢ Here E specifies type of objects that the list will hold.
➢ ArrayList supports dynamic arrays that can grow as needed.
➢ In java, standard arrays are of fixed length.
➢ ArrayList has the constructors shown here:
ArrayList( )
ArrayList(Collection c)
➢ The first constructor builds an empty list. The second
constructor builds a list that is initialized with the elements of
the collection c.
Ex:-
// Demonstrate ArrayList.
import [Link].*;
class ArrayListDemo {
public static void main(String args[]) {
ArrayList<String> al = new ArrayList<String>();
[Link]("Initial size of al: " + [Link]());
[Link]("C");
[Link]("A"); Output:
Initial size of al: 0
[Link]("E"); Size of al after additions: 7
[Link]("B"); Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
[Link]("D"); Contents of al: [C, A2, E, B, D]
[Link]("F");
[Link](1, "A2");
[Link]("Size of al after additions: " + [Link]());
[Link]("Contents of al: " + al);
[Link]("F");
[Link](2);
[Link]("Size of al after deletions: " + [Link]());
[Link]("Contents of al: " + al);
}
} 64
The LinkedList Class
➢ The LinkedList class implements the List , Deque, and
Queue interfaces.
➢ LinkedList Class is a generic class that has this declaration:
class LinkedList<E>
➢ It provides a linked-list data structure. It has the two
constructors, shown here:
▪ LinkedList( )
▪ LinkedList(Collection c)
➢ The first constructor builds an empty linked list. The second
constructor builds a linked list that is initialized with the
elements of the collection c.
➢ It can store the duplicate elements.
Ex:-
// Demonstrate LinkedList.
import [Link].*;
class LinkedListDemo {
public static void main(String args[]) {
// create a linked list
LinkedList<String> llist = new LinkedList<String>();
[Link]("F");
[Link]("B");
[Link]("D");
[Link]("E");
[Link]("C");
[Link]("Z");
[Link]("A");
[Link](1, "A2");
[Link]("Original contents of llist: " + llist);
// remove elements from the linked list
[Link]("F");
[Link](2);
[Link]("Contents of llist after deletion: " + llist);
// remove first and last elements
[Link]();
[Link]();
[Link]("llist after deleting first and last: "+ llist);
}
}

Output:
Original contents of llist: [A, A2, F, B, D, E, C, Z]
Contents of llist after deletion: [A, A2, D, E, C, Z]
llist after deleting first and last: [A2, D, E, C]
The TreeSet Class
➢ TreeSet provides an implementation of the SortedSet
interface. Objects are stored in sorted, ascending order.
➢ The following constructors are defined:
TreeSet( )
TreeSet(Collection c)
➢ The first constructor builds an empty. The second constructor
builds a TreeSet that is initialized with the elements of the
collection c.
➢ It does not allow to store duplicate elements.

68
Ex :
import [Link].*;
class TreeSetExample{
public static void main(String args[])
{
TreeSet<String> ts=new TreeSet<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ajay");
[Link]("Pavan");
[Link](ts);
[Link]([Link]());
[Link]([Link]());
}
}

69
Algorithms
• The collections framework defines several algorithms
that can be applied to collections.

• These algorithms are defined as static methods


within the Collections class.

70
Method Description
static int binarySearch(List list, Searches for value in list. The list must be
Object value) sorted. Returns the position of value in
list,or−1 if Value is not found
static void sort(List list) Sorts the elements of list as determined by
their natural Ordering

static Object max(Collection c) Returns the maximum element in c. The


collection need not be sorted

static Object min(Collection c) Returns the minimum element in c. The


collection need not be sorted

71
static void swap(List list, int idx1, int Exchanges the elements in list at
idx2) the indices specified by idx1 and
idx2.
static void shuffle(List list) Shuffles (i.e., randomizes) the
elements in list.

72
Example: (binary search)
import [Link].*;
class AlgorithmsDemo1
{
public static void main(String args[])
{
ArrayList<String> al=new ArrayList<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ajay");
[Link]("Pavan");
[Link](al);
[Link]( "List After Sorting\n"+al);
[Link]( "Enter Element to be searched ");
Scanner s=new Scanner([Link]);
String element=[Link]();
int loc=[Link](al,element);
if(loc>=0)
[Link]("Element found, index="+loc );
else
[Link]("Element not found" );

}
} 73
Example: ( Sorting )
import [Link].*;
class AlgorithmsDemo2
{
public static void main(String args[])
{
ArrayList<String> al=new ArrayList<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ajay");
[Link]("Pavan");

[Link]( "List Before Sorting\n"+al);


[Link]( al);
[Link]( "List After Sorting\n"+al);

}
}

74
Example: (max, min and reverse)
import [Link].*;
public class MaxMinRev {
public static void main(String args[]) {
ArrayList<Integer> al=new ArrayList<Integer>();

[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link](50);

[Link]("List values: "+al);


[Link]("Minimum is :"+[Link](al));
[Link](“Maximum is :"+[Link](al));

[Link](al);

[Link]("List values after reverse: "+al);


}
}
75

You might also like