0% found this document useful (0 votes)
50 views

JAVA UNIT4 - M.Bommy PDF

This document discusses Java I/O streams and collection framework classes. It covers byte stream classes like FileInputStream and FileOutputStream that can be used to read and write bytes from/to files. It also discusses character stream classes and the collection framework hierarchy including common classes like ArrayList, LinkedList, HashSet and TreeSet.

Uploaded by

Vishnu Vardhan
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)
50 views

JAVA UNIT4 - M.Bommy PDF

This document discusses Java I/O streams and collection framework classes. It covers byte stream classes like FileInputStream and FileOutputStream that can be used to read and write bytes from/to files. It also discusses character stream classes and the collection framework hierarchy including common classes like ArrayList, LinkedList, HashSet and TreeSet.

Uploaded by

Vishnu Vardhan
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
You are on page 1/ 80

20CSE108 JAVA PROGRAMMING

II-II Sem CSE – D


Prepared by: M.BOMMY, AP/CSE.
UNIT IV
I/O STREAMS AND COLLECTION FRAME WORK CLASSES
I/O Streams: Byte Stream Classes and Character Stream
Classes.

Collection Framework: Hierarchy of collection framework,


Array-List, Linked-List, Vector, Stack, Queue, Priority Queue,
Hash Set, Linked Hash Set, Tree Set.
JAVA I/O STREAMS
 Stream:
 streams are the sequence of data that are read from the source and written to the destination.
 an object that either delivers data to its destination (screen, file, etc.) or that takes data from
a source (keyboard, file, etc.)
 it acts as a buffer between the data source and destination.
 Input stream: A stream that provides input to a program. Is used to read data from the source.
 System.in is an input stream
 Output stream: A stream that accepts output from a program. Is used to write data to the
destination.
 System.out is an output stream
 A stream connects a program to an I/O object
 System.out connects a program to the screen
 System.in connects a program to the keyboard
TYPES OF STREAMS
 Depending upon the data a stream holds, it can be classified into:
Byte Stream
Character Stream
The Stream Classes
 Java’s stream-based I/O is built upon four abstract classes: InputStream,
OutputStream, Reader, and Writer. They are used to create several concrete stream
subclasses. Although your programs perform their I/O operations through
concrete subclasses, the top-level classes define the basic functionality common to
all stream classes.
 InputStream and OutputStream are designed for byte streams.
 Reader and Writer are designed for character streams.
 The byte stream classes and the character stream classes form separate hierarchies.
 In general, you should use the character stream classes when working with
characters or strings and use the byte stream classes when working with bytes or
other binary objects.
THE BYTE STREAMS
 The byte stream classes provide a rich environment for handling byte-oriented
I/O. A byte stream can be used with any type of object, including binary data. This
versatility makes byte streams important to many types of programs.
 ByteStream classes are used to read bytes from the input stream and write bytes to
the output stream. In other words, we can say that ByteStream classes read/write
the data of 8-bits. We can store video, audio, characters, etc., by using ByteStream
classes. These classes are part of the java.io package.
 The ByteStream classes are divided into two types of classes, i.e., InputStream and
OutputStream. These classes are abstract and the super classes of all the
Input/Output stream classes.
InputStream
 InputStream is an abstract class that defines Java’s model of streaming byte
input. It implements the AutoCloseable and Closeable interfaces. Most of the
methods in this class will throw an IOException when an I/O error occurs.
 The InputStream class provides methods to read bytes from a file, console or
memory. It is an abstract class and can't be instantiated; however, various
classes inherit the InputStream class and override its methods. The subclasses
of InputStream class are given in the following table.
Input Stream Classes
CLASS DESCRIPTION
BufferedInputStream contains methods to read bytes from the buffer (memory area)
ByteArrayInputStream contains methods to read bytes from a byte array
DataInputStream contains methods to read Java primitive data types
FileInputStream contains methods to read bytes from a file
FilterInputStream contains methods to read bytes from other input streams which it
uses as its basic source of data
ObjectInputStream contains methods to read objects
PipedInputStream contains methods to read from a piped output stream. A piped
input stream must be connected to a piped output stream
SequenceInputStream contains methods to concatenate multiple input streams and then
read from the combined stream
Input Stream Class Methods
 The InputStream class contains various methods to read the data from an
input stream. These methods are overridden by the classes that inherit the
InputStream class. However, the methods are given in the following table.
Method Description
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.
void mark(int numBytes) Places a mark at the current point in the input stream that will remain valid until
numBytes bytes are read.
boolean markSupported( ) Returns true if mark( ) / reset( ) are supported by the invoking stream.
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 read(byte buffer[ ]) Attempts to read up to buffer.length bytes into buffer and returns the actual number
of bytes that were successfully read. –1 is returned when the end of the file is
encountered.
int read(byte buffer[ ], int offset, int numBytes) Attempts to read up to numBytes bytes into buffer starting at buffer[offset], returning
the number of bytes successfully read. –1 is returned when the end of the file is
void reset( Resets the input pointer to the previously set mark.
long skip(long numBytes) Ignores (that is, skips) numBytes bytes of input, returning the number of bytes actually
ignored.
OutputStream
 OutputStream is an abstract class that defines streaming byte output. It
implements the AutoCloseable, Closeable, and Flushable interfaces. Most of the
methods defined by this class return void and throw an IOException in the case of
I/O errors.
 It is the superclass of all the output stream classes. This class can't be instantiated;
however, it is inherited by various subclasses that are given in the following table.
Output Stream Classes
CLASS DESCRIPTION
BufferedOutputStream Contains methods to write bytes into the buffer
ByteArrayOutputStream Contains methods to write bytes into a byte array
DataOutputStream Contains methods to write Java primitive data types
FileOutputStream Contains methods to write bytes to a file
FilterOutputStream Contains methods to write to other output streams
ObjectOutputStream Contains methods to write objects
PipedOutputStream Contains methods to write to a piped output stream
PrintStream Contains methods to print Java primitive data types
Output Stream Class Methods
 The OutputStream class provides various methods to write bytes to the output
streams. The methods are given in the following table.
Method Description

void close( ) Closes the output stream. Further write attempts will generate an
IOException.
void flush( ) Finalizes the output state so that any buffers are cleared. That is, it
flushes the output
void write(int b) Writes a single byte to an output stream. Note that the parameter is
an int, which allows you to call write( ) with an expression without
having to cast it back to byte.
void write(byte buffer[ ]) Writes a complete array of bytes to an output stream.
void write(byte buffer[ ], int offset, int Writes a subrange of numBytes bytes from the array buffer, beginning at
numBytes) buffer[offset].
FileInputStream
 The FileInputStream class creates an InputStream that you can use to read bytes from a file.
 Two commonly used constructors are shown here:
• FileInputStream(String filePath)
• FileInputStream(File fileObj)
 Either can throw a FileNotFoundException.
 Here, filePath is the full path name of a file, and fileObj is a File object that describes the file.
 The following example creates two FileInputStreams that use the same disk file and each of
the two constructors:
o FileInputStream f0 = new FileInputStream("/autoexec.bat")
o File f = new File("/autoexec.bat");
o FileInputStream f1 = new FileInputStream(f);
 FileInputStream overrides six of the methods in the abstract class InputStream. The
mark( ) and reset( ) methods are not overridden, and any attempt to use reset( ) on
a FileInputStream will generate an IOException.
FileOutputStream
 FileOutputStream creates an OutputStream that you can use to write bytes to a
file. It implements the AutoCloseable, Closeable, and Flushable interfaces.
 Four of its constructors are shown here:
o FileOutputStream(String filePath)
o FileOutputStream(File fileObj)
o FileOutputStream(String filePath, boolean append)
o FileOutputStream(File fileObj, boolean append)
 They can throw a FileNotFoundException. Here, filePath is the full path name of a
file, and fileObj is a File object that describes the file. If append is true, the file is opened in
append mode.
ByteArrayInputStream
 ByteArrayInputStream is an implementation of an input stream that uses a byte
array as the source. This class has two constructors, each of which requires a byte
array to provide the data source:
• ByteArrayInputStream(byte array [ ])
• ByteArrayInputStream(byte array [ ], int start, int numBytes)
 Here, array is the input source.The second constructor creates an InputStream from a subset
of the byte array that begins with the character at the index specified by start and is
numBytes long.
 The close( ) method has no effect on a ByteArrayInputStream.
 Therefore, it is not necessary to call close( ) on a ByteArrayInputStream, but doing
so is not an error.
 A ByteArrayInputStream implements both mark( ) and reset( ).
ByteArrayOutputStream
 ByteArrayOutputStream is an implementation of an output stream that uses a byte array
as the destination.
 ByteArrayOutputStream has two constructors, shown here:
o ByteArrayOutputStream( )
o ByteArrayOutputStream(int numBytes)
 In the first form, a buffer of 32 bytes is created. In the second, a buffer is created with a
size equal to that specified by numBytes. The buffer is held in the protected buf field of
ByteArrayOutputStream.The buffer size will be increased automatically, if needed.
 The number of bytes held by the buffer is contained in the protected count field of
ByteArrayOutputStream.
 The close( ) method has no effect on a ByteArrayOutputStream. Therefore, it is not
necessary to call close( ) on a ByteArrayOutputStream, but doing so is not an error.
Filtered Byte Streams
 Filtered streams are simply wrappers around underlying input or output streams that transparently
provide some extended level of functionality. These streams sit on top of an already
existing output stream (the underlying output stream) which it uses as its basic sink of data,
but possibly transforming the data along the way or providing additional functionality.
 These streams are typically accessed by methods that are expecting a generic stream,
which is a superclass of the filtered streams.
 Typical extensions are buffering, character translation, and raw data translation.
 The filtered byte streams are FilterInputStream and FilterOutputStream.
 Their constructors are shown here:
o FilterOutputStream(OutputStream os)
o FilterInputStream(InputStream is)
 The methods provided in these classes are identical to those in InputStream and
OutputStream.
Buffered Byte Streams
 For the byte-oriented streams, a buffered stream extends a filtered stream class by
attaching a memory buffer to the I/O stream.
 This buffer allows Java to do I/O operations on more than a byte at a time, thereby
improving performance.
 Because the buffer is available, skipping, marking, and resetting of the stream
become possible.
 The buffered byte stream classes are BufferedInputStream and
BufferedOutputStream.
BufferedInputStream
 Buffering I/O is a very common performance optimization. Java’s BufferedInputStream
class allows you to "wrap" any InputStream into a buffered stream to improve
performance.
 BufferedInputStream has two constructors:
o BufferedInputStream(InputStream inputStream)
o BufferedInputStream(InputStream inputStream, int bufSize)
 The first form creates a buffered stream using a default buffer size. In the second, the size
of the buffer is passed in bufSize.
 BufferedInputStream also supports the mark( ) and reset( ) methods.
 This support is reflected by BufferedInputStream.markSupported( ) returning true.
BufferedOutputStream
 Unlike buffered input, buffering output does not provide additional
functionality.
 Buffers for output in Java are there to increase performance. Here are the
two available constructors:
o BufferedOutputStream(OutputStream outputStream)
o BufferedOutputStream(OutputStream outputStream, int bufSize)
 The first form creates a buffered stream using the default buffer size. In the
second form, the size of the buffer is passed in bufSize.
PushbackInputStream
 One of the novel uses of buffering is the implementation of pushback. Pushback is used on
an input stream to allow a byte to be read and then returned (that is, "pushed back") to
the stream. The PushbackInputStream class implements this idea. It provides a mechanism
to "peek" at what is coming from an input stream without disrupting it.
 PushbackInputStream has the following constructors:
 PushbackInputStream(InputStream inputStream)
 PushbackInputStream(InputStream inputStream, int numBytes)
 The first form creates a stream object that allows one byte to be returned to the input
stream.
 The second form creates a stream that has a pushback buffer that is numBytes long. This
allows multiple bytes to be returned to the input stream.
 Beyond the familiar methods of InputStream, PushbackInputStream provides unread( ),
shown here:
o void unread(int b)
o void unread(byte buffer [ ])
o void unread(byte buffer, int offset, int numBytes)
 The first form pushes back the low-order byte of b. This will be the next byte returned by
a subsequent call to read( ). The second form pushes back the bytes in buffer. The third
form pushes back numBytes bytes beginning at offset from buffer.
 An IOException will be thrown if there is an attempt to push back a byte when the
pushback buffer is full.
SequenceInputStream
 The SequenceInputStream class allows you to concatenate multiple InputStreams, ie reads
data from multiple streams. The construction of a SequenceInputStream is different from
any other InputStream.
 A SequenceInputStream constructor uses either a pair of InputStreams or an Enumeration
of InputStreams as its argument:
 SequenceInputStream(InputStream first, InputStream second)
 SequenceInputStream(Enumeration <? extends InputStream> streamEnum)
 Operationally, the class fulfills read requests from the first InputStream until it runs out
and then switches over to the second one. In the case of an Enumeration, it will continue
through all of the InputStreams until the end of the last one is reached. When the end of
each file is reached, its associated stream is closed. Closing the stream created by
SequenceInputStream causes all unclosed streams to be closed.
PrintStream
 The PrintStream class provides all of the output capabilities we have been using from the System
file handle, System.out. This makes PrintStream one of Java’s most often used classes. It
implements the Appendable,AutoCloseable, Closeable, and Flushable interfaces.
 PrintStream defines several constructors.The one of them is:
 PrintStream(OutputStream outputStream)
 PrintStream(OutputStream outputStream, boolean autoFlushingOn)
 PrintStream(OutputStream outputStream, boolean autoFlushingOn String charSet)
throws UnsupportedEncodingException
 Here, outputStream specifies an open OutputStream that will receive output. The autoFlushingOn
parameter controls whether the output buffer is automatically flushed every time a newline (\n)
character or a byte array is written or when println( ) is called. If autoFlushingOn is true, flushing
automatically takes place. If it is false, flushing is not automatic. The first constructor does not
automatically flush.You can specify a character encoding by passing its name in charSet.
 The next set of constructors gives you an easy way to construct a PrintStream that writes its
output to a file:
 PrintStream(File outputFile) throws FileNotFoundException
 PrintStream(File outputFile, String charSet) throws FileNotFoundException,
UnsupportedEncodingException
 PrintStream(String outputFileName) throws FileNotFoundException
 PrintStream(String outputFileName, String charSet) throws FileNotFoundException,
UnsupportedEncodingException
 These allow a PrintStream to be created from a File object or by specifying the name of a file. In
either case, the file is automatically created. Any preexisting file by the same name is destroyed.
Once created, the PrintStream object directs all output to the specified file. You can specify a
character encoding by passing its name in charSet.
 PrintStream supports the print( ) and println( ) methods for all types, including
Object.
 If an argument is not a primitive type, the PrintStream methods will call the
object’s toString( ) method and then display the result.
 Somewhat recently (with the release of JDK 5), the printf( ) method was added to
PrintStream. It allows you to specify the precise format of the data to be written.
 The printf( ) method uses the Formatter class to format data. It then writes this
data to the invoking stream.
DataOutputStream and DataInputStream
 DataOutputStream and DataInputStream enable you to write or read primitive
data to or from a stream.
 They implement the DataOutput and DataInput interfaces, respectively.
 These interfaces define methods that convert primitive values to or from a
sequence of bytes.
 These streams make it easy to store binary data, such as integers or floating-point
values, in a file.
DataOutputStream
 DataOutputStream extends FilterOutputStream, which extends OutputStream. In
addition to implementing DataOutput, DataOutputStream also implements
AutoCloseable, Closeable, and Flushable.
 DataOutputStream defines the following constructor:
 DataOutputStream(OutputStream outputStream)
 Here, outputStream specifies the output stream to which data will be written.
When a DataOutputStream is closed (by calling close( )), the underlying stream
specified by outputStream is also closed automatically.
 DataOutputStream supports all of the methods defined by its superclasses.
However, it is the methods defined by the DataOutput interface, which it
implements, that make it interesting.
 DataOutput defines methods that convert values of a primitive type into a byte
sequence and then writes it to the underlying stream. Here is a sampling of these
methods:
 final void writeDouble(double value) throws IOException
 final void writeBoolean(boolean value) throws IOException
 final void writeInt(int value) throws IOException
 Here, value is the value written to the stream.
DataInputStream
 DataInputStream is the complement of DataOuputStream. It extends
FilterInputStream, which extends InputStream. In addition to implementing the
DataInput interface, DataInputStream also implements AutoCloseable and
Closeable.
 Here is its only constructor:
 DataInputStream(InputStream inputStream)
 Here, inputStream specifies the input stream from which data will be read. When a
DataInputStream is closed (by calling close( )), the underlying stream specified by
inputStream is also closed automatically.
 DataInputStream supports all of the methods of its superclasses, but it is the
methods defined by the DataInput interface that make it unique. These methods
read a sequence of bytes and convert them into values of a primitive type.
 Here is a sampling of these methods:
 final double readDouble( ) throws IOException
 final boolean readBoolean( ) throws IOException
 final int readInt( ) throws IOException
THECHARACTER STREAM CLASSES
 While the byte stream classes provide sufficient functionality to handle any type of I/O
operation, they cannot work directly with Unicode characters. The java.io package
provides CharacterStream classes to overcome the limitations of ByteStream classes,
which can only handle the 8-bit bytes and is not compatible to work directly with the
Unicode characters. Since one of the main purposes of Java is to support the "write once,
run anywhere" philosophy, it was necessary to include direct I/O support for characters.
 CharacterStream classes are used to work with 16-bit Unicode characters. They can
perform operations on characters, char arrays and Strings.
 However, the CharacterStream classes are mainly used to read characters from the source
and write them to the destination. For this purpose, the CharacterStream classes are
divided into two types of classes, I.e., Reader class andWriter class.
 At the top of the character stream hierarchies are the Reader and Writer abstract
classes.
Reader
 Reader is an abstract class that defines Java’s model of streaming character input.
 It implements the AutoCloseable, Closeable, and Readable interfaces. All of the
methods in this class (except for markSupported( )) will throw an IOException on
error conditions.
 Following table provides a synopsis of the methods in Reader.
Writer
 Writer is an abstract class that defines streaming character output.
 It implements the AutoCloseable, Closeable, Flushable, and Appendable interfaces.
 All of the methods in this class throw an IOException in the case of errors.
 The following table shows a synopsis of the methods in Writer.
FileReader
 The FileReader class creates a Reader that you can use to read the contents of a
file.
 Two commonly used constructors are shown here:
 FileReader(String filePath)
 FileReader(File fileObj)
 Either can throw a FileNotFoundException. Here, filePath is the full path name of a
file, and fileObj is a File object that describes the file.
FileWriter
 FileWriter creates a Writer that you can use to write to a file.
 Four commonly used constructors are shown here:
 FileWriter(String filePath)
 FileWriter(String filePath, boolean append)
 FileWriter(File fileObj)
 FileWriter(File fileObj, boolean append)
 They can all throw an IOException. Here, filePath is the full path name of a file, and fileObj is
a File object that describes the file. If append is true, then output is appended to the end of the
file.
 Creation of a FileWriter is not dependent on the file already existing. FileWriter will
create the file before opening it for output when you create the object. In the case where
you attempt to open a read-only file, an IOException will be thrown.
CharArrayReader
 CharArrayReader is an implementation of an input stream that uses a character
array as the source.
 This class has two constructors, each of which requires a character array to provide
the data source:
 CharArrayReader(char array [ ])
 CharArrayReader(char array [ ], int start, int numChars)
 Here, array is the input source. The second constructor creates a Reader from a subset of your
character array that begins with the character at the index specified by start and is
numChars long.
 The close( ) method implemented by CharArrayReader does not throw any
exceptions.
CharArrayWriter
 CharArrayWriter is an implementation of an output stream that uses an array as
the destination.
 CharArrayWriter has two constructors, shown here:
o CharArrayWriter( )
o CharArrayWriter(int numChars)
 In the first form, a buffer with a default size is created. In the second, a buffer is
created with a size equal to that specified by numChars. The buffer is held in the buf
field of CharArrayWriter. The buffer size will be increased automatically, if needed.
The number of characters held by the buffer is contained in the count field of
CharArrayWriter. Both buf and count are protected fields.
 The close( ) method has no effect on a CharArrayWriter.
BufferedReader
 BufferedReader improves performance by buffering input.
 It has two constructors:
o BufferedReader(Reader inputStream)
o BufferedReader(Reader inputStream, int bufSize)
 The first form creates a buffered character stream using a default buffer size. In the
second, the size of the buffer is passed in bufSize.
BufferedWriter
 A BufferedWriter is a Writer that buffers output. Using a BufferedWriter can
improve performance by reducing the number of times data is actually physically
written to the output device.
 A BufferedWriter has these two constructors:
 BufferedWriter(Writer outputStream)
 BufferedWriter(Writer outputStream, int bufSize)
 The first form creates a buffered stream using a buffer with a default size. In the
second, the size of the buffer is passed in bufSize.
PushbackReader
 The PushbackReader class allows one or more characters to be returned to the input
stream. This allows you to look ahead in the input stream.
 Here are its two constructors:
o PushbackReader(Reader inputStream)
o PushbackReader(Reader inputStream, int bufSize)
 The first form creates a buffered stream that allows one character to be pushed back. In
the second, the size of the pushback buffer is passed in bufSize.
 Closing a PushbackReader also closes the underlying stream specified by inputStream.
 PushbackReader provides unread( ), which returns one or more characters to the
invoking input stream. It has the three forms shown here:
o void unread(int ch) throws IOException
o void unread(char buffer [ ]) throws IOException
o void unread(char buffer [ ], int offset, int numChars) throws IOException
PrintWriter
 PrintWriter is essentially a character-oriented version of PrintStream. It implements the
Appendable,AutoCloseable, Closeable, and Flushable interfaces.
 PrintWriter has several constructors. The following have been supplied by PrintWriter
from the start:
 PrintWriter(OutputStream outputStream)
 PrintWriter(OutputStream outputStream, boolean autoFlushingOn)
 PrintWriter(Writer outputStream)
 PrintWriter(Writer outputStream, boolean autoFlushingOn)
 Here, outputStream specifies an open OutputStream that will receive output. The autoFlushingOn
parameter controls whether the output buffer is automatically flushed every time println( ),
printf( ), or format( ) is called. If autoFlushingOn is true, flushing automatically takes place.
If false, flushing is not automatic. Constructors that do no specify the autoFlushingOn
parameter do not automatically flush.
 The next set of constructors gives you an easy way to construct a PrintWriter that writes
its output to a file.
 PrintWriter(File outputFile) throws FileNotFoundException
 PrintWriter(File outputFile, String charSet) throws FileNotFoundException,
UnsupportedEncodingException
 PrintWriter(String outputFileName) throws FileNotFoundException
 PrintWriter(String outputFileName, String charSet) throws FileNotFoundException,
UnsupportedEncodingException
 These allow a PrintWriter to be created from a File object or by specifying the name of a
file. In either case, the file is automatically created.
 PrintWriter also supports the printf( ) method.
The Collection Framework
 The Collections Framework defines several core interfaces.
Hierarchy of the Collection Framework
The ArrayList Class
 The ArrayList class extends AbstractList and implements the List interface.
 ArrayList is a generic class that has this declaration:
• class ArrayList<E>
 Here, E specifies the type of objects that the list will hold.
 ArrayList supports dynamic arrays that can grow as needed.
 In Java, standard arrays are of a fixed length. After arrays are created, they cannot
grow or shrink, which means that you must know in advance how many elements
an array will hold.
 But, sometimes, you may not know until run time precisely how large an array
you need. To handle this situation, the Collections Framework defines ArrayList.
 An ArrayList can dynamically increase or decrease in size.
 Array lists are created with an initial size.
 When this size is exceeded, the collection is automatically enlarged. When objects
are removed, the array can be shrunk
 ArrayList has the constructors shown here:
• ArrayList( )
• ArrayList(Collection<? extends E> c)
• ArrayList(int capacity).
COLLECTION FRAMEWORK : LinkedList
 The LinkedList class extends AbstractSequentialList and implements the List, Deque, and
Queue interfaces. It provides a linked-list data structure, which is a linear data structure
where the elements are not stored in contiguous locations.
 LinkedList is a generic class that has this declaration:
 class LinkedList<E>
 Here, E specifies the type of objects that the list will hold.
 LinkedList has the two constructors shown here:
• LinkedList( )
• LinkedList(Collection<? extends E> 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.
 Because LinkedList implements the Deque interface, you have access to the
methodsdefined by Deque.
 For example, to add elements to the start of a list, you can use addFirst( ) or
offerFirst( ).
 To add elements to the end of the list, use addLast( ) or offerLast( ).
 To obtain the first element, you can use getFirst( ) or peekFirst( ). To obtain the
last element, use getLast( ) or peekLast( ).
 To remove the first element, use removeFirst( ) or pollFirst( ).
 To remove the last element, use removeLast( ) or pollLast( ).
COLLECTION FRAMEWORK: HashSet
 HashSet extends AbstractSet and implements the Set interface. It creates a
collection that uses a hash table for storage.
 HashSet is a generic class that has this declaration:
• class HashSet<E>
 Here, E specifies the type of objects that the set will hold.
 A hash table stores information by using a mechanism called hashing.
 In hashing, the informational content of a key is used to determine a unique value,
called its hash code.
 The hash code is then used as the index at which the data associated with the key is
stored.
 The transformation of the key into its hash code is performed automatically.
 The advantage of hashing is that it allows the execution time of add( ), contains( ),
remove( ), and size( ) to remain constant even for large sets.
 The following constructors are defined:
 HashSet( )
 HashSet(Collection<? extends E> c)
 HashSet(int capacity)
 HashSet(int capacity, float fillRatio)
 It is important to note that HashSet does not guarantee the order of its elements,
because the process of hashing doesn’t usually lend itself to the creation of sorted
sets.
COLLECTION FRAMEWORK: LinkedHashSet
 The LinkedHashSet class extends HashSet and adds no members of its own.
 It is a generic class that has this declaration:
• class LinkedHashSet<E>
 Here, E specifies the type of objects that the set will hold. Its constructors parallel those
in HashSet.
 LinkedHashSet maintains a linked list of the entries in the set, in the order in which they
were inserted.
 This allows insertion-order iteration over the set. That is, when cycling through a
LinkedHashSet using an iterator, the elements will be returned in the order in which they
were inserted.
COLLECTION FRAMEWORK: TreeSet
 TreeSet extends AbstractSet and implements the NavigableSet interface. It
creates a collection that uses a tree for storage.
 Objects are stored in sorted, ascending order.
 Access and retrieval times are quite fast, which makes TreeSet an excellent
choice when storing large amounts of sorted information that must be found
quickly.
 TreeSet is a generic class that has this declaration:
• class TreeSet<E>
 Here, E specifies the type of objects that the set will hold.
 TreeSet has the following constructors:
• TreeSet( )
• TreeSet(Collection<? extends E> c)
• TreeSet(Comparator<? super E> comp)
• TreeSet(SortedSet<E> ss)
ArrayList Vs Vector in Java
COLLECTION FRAMEWORK: Vector
 Vector implements a dynamic array.
 It is similar to ArrayList, but with two differences:
Vector is synchronized, and it contains many legacy methods that duplicate
the functionality of methods defined by the Collections Framework. With the
advent of collections, Vector was reengineered to extend AbstractList and to
implement the List interface.
 Vector is declared like this:
class Vector<E>
Here, E specifies the type of element that will be stored.
 Here are the Vector constructors:
• Vector( )
• Vector(int size)
• Vector(int size, int incr)
• Vector(Collection<? extends E> c)
COLLECTION FRAMEWORK: Stack
 The stack is a linear data structure that is used to store the collection of objects. It
is based on Last-In-First-Out (LIFO). Provides different operations such as push,
pop, search, etc.
 Stack is a subclass of Vector that implements a standard last-in, first-out stack.
Stack only defines the default constructor, which creates an empty stack.
 Stack is declared as shown here:
• class Stack<E>
 Here, E specifies the type of element stored in the stack.
 Stack includes all the methods defined by Vector and adds several of its own, as
shown in the following table
In Java, Stack is a class that falls under the Collection
framework that extends the Vector class. It also
implements interfaces List, Collection, Iterable,
Cloneable, Serializable.
Collection Framework –Stack Class – PUSH Operation
import java.util.Stack; // pushing elements into stack
public class StackEmptyMethodExample stk.push(78);
{ stk.push(113);
public static void main(String[] args) stk.push(90);
{ stk.push(120);
//creating an instance of Stack class //prints elements of the stack
Stack<Integer> stk= new Stack<>(); System.out.println("Elements in Stack: " + st
// checking stack is empty or not k);
boolean result = stk.empty(); result = stk.empty();
System.out.println("Is the stack empty? " + r System.out.println("Is the stack empty? " + r
esult); esult);
}
}
OUTPUT??
Collection Framework –Stack Class – POP Operation
import java.util.Stack; // Remove element stacks
String element = animals.pop();
class Main { System.out.println("Removed
public static void main(String[] args) Element: " + element);
{ }
Stack<String> animals= new }
Stack<>(); OUTPUT:
Initial Stack: [Dog, Horse, Cat]
// Add elements to Stack Removed Element: Cat
animals.push("Dog");
animals.push("Horse");
animals.push("Cat");
System.out.println("Initial Stack:
" + animals);
Collection Framework –Stack Class – peek() Method

import java.util.Stack; // Access element from the top


String element = animals.peek();
class Main { System.out.println("Element at
public static void main(String[] args) top: " + element);
{
Stack<String> animals= new }
Stack<>(); }
OUTPUT:
// Add elements to Stack Stack: [Dog, Horse, Cat]
animals.push("Dog"); Element at top: Cat
animals.push("Horse");
animals.push("Cat");
System.out.println("Stack: " +
animals);
COLLECTION FRAMEWORK: Queue
 The interface Queue is available in the java.util package and does extend the
Collection interface. It is used to keep the elements that are processed in the First
In First Out (FIFO) manner. It is an ordered list of objects, where insertion of
elements occurs at the end of the list, and removal of elements occur at the
beginning of the list.
 Queue is a generic interface that has this declaration:
• interface Queue<E>
 Here, E specifies the type of objects that the queue will hold.
 The methods declared by Queue are shown in following table.
 Several methods throw a ClassCastException when an object is incompatible with
the elements in the queue.
 A NullPointerException is thrown if an attempt is made to store a null object and
null elements are not allowed in the queue.
 An IllegalArgumentException is thrown if an invalid argument is used.
 An IllegalStateException is thrown if an attempt is made to add an element to a
fixed-length queue that is full.
 A NoSuchElementException is thrown if an attempt is made to remove an element
from an empty queue.
 Queue offers several points of interest.
 First, elements can only be removed from the head of the queue.
 Second, there are two methods that obtain and remove elements: poll( ) and
remove(). The difference between them is that poll( ) returns null if the queue is
empty, but remove( ) throws an exception.
 Third, there are two methods, element( ) and peek( ), that obtain but don’t remove
the element at the head of the queue. They differ only in that element( ) throws an
exception if the queue is empty, but peek( ) returns null.
 Finally, notice that offer( ) only attempts to add an element to a queue. Because
some queues have a fixed length and might be full, offer( ) can fail.
In order to use the functionalities of Queue, we need to use classes that implement it:
 ArrayDeque
 LinkedList
 PriorityQueue
How to use Queue?
In Java, we must import java.util.Queue package in order to use Queue.
COLLECTION FRAMEWORK: PriorityQueue
 PriorityQueue extends AbstractQueue and implements the Queue interface.
 It creates a queue that is prioritized based on the queue’s comparator.
 PriorityQueue is a generic class that has this declaration:
• class PriorityQueue<E>
 Here, E specifies the type of objects stored in the queue. PriorityQueues are
dynamic, growing as necessary.
 PriorityQueue defines the six constructors shown here:
• PriorityQueue( )
• PriorityQueue(int capacity)
• PriorityQueue(Comparator<? super E> comp) (Added by JDK 8.)
• PriorityQueue(int capacity, Comparator<? super E> comp)
• PriorityQueue(Collection<? extends E> c)
• PriorityQueue(PriorityQueue<? extends E> c)
• PriorityQueue(SortedSet<? extends E> c)
 The first constructor builds an empty queue. Its starting capacity is 11. The second
constructor builds a queue that has the specified initial capacity. The third constructor specifies
a comparator, and the fourth builds a queue with the specified capacity and comparator. The
last three constructors create queues that are initialized with the elements of the collection
passed in c. In all cases, the capacity grows automatically as elements are added.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy