Java-summarized-notes
Why Collections Framework?
The collections framework was designed to meet several goals, such as −
• The framework had to be high-performance. The implementations for the fundamental
collections (dynamic arrays, linked lists, trees, and hashtables) were to be highly efficient.
• The framework had to allow different types of collections to work in a similar manner and
with a high degree of interoperability.
• The framework had to extend and/or adapt a collection easily.
Towards this end, the entire collections framework is designed around a set of standard
interfaces. Several standard implementations such as LinkedList, HashSet,and TreeSet, of
these interfaces are provided that you may use as-is and you may also implement your own
collection, if you choose.\
h interface −
[Link].
Interface & Description
The Collection Interface
This enables you to work
1 with groups of objects; it
is at the top of the
collections hierarchy.
The List Interface
This extends Collection
2 and an instance of List
stores an ordered
collection of elements.
The Set
This extends Collection to
3
handle sets, which must
contain unique elements.
The SortedSet
4 This extends Set to
handle sorted sets.
The Map
5 This maps unique keys to
values.
The [Link]
This describes an element
6 (a key/value pair) in a
map. This is an inner class
of Map.
The SortedMap
This extends Map so that
7
the keys are maintained
in an ascending order.
The Enumeration
This is legacy interface
defines the methods by
which you can enumerate
8 (obtain one at a time) the
elements in a collection
of objects. This legacy
interface has been
superceded by Iterator.
Java Collection Classes
Java provides a set of standard collection classes that implement Collection interfaces. Some
of the classes provide full implementations that can be used as-is and others are abstract
class, providing skeletal implementations that are used as starting points for creating concrete
collections.
The standard collection classes are summarized in the following table −
[Link].
Class & Description
AbstractCollection
1 Implements most of the
Collection interface.
AbstractList
Extends
2 AbstractCollection and
implements most of the
List interface.
AbstractSequentialList
Extends AbstractList for
use by a collection that
3
uses sequential rather
than random access of its
elements.
LinkedList
Implements a linked list
4
by extending
AbstractSequentialList.
ArrayList
Implements a dynamic
5
array by extending
AbstractList.
AbstractSet
Extends
6 AbstractCollection and
implements most of the
Set interface.
HashSet
7 Extends AbstractSet for
use with a hash table.
LinkedHashSet
8 Extends HashSet to allow
insertion-order iterations.
TreeSet
Implements a set stored
9
in a tree. Extends
AbstractSet.
AbstractMap
10 Implements most of the
Map interface.
HashMap
11 Extends AbstractMap to
use a hash table.
TreeMap
12 Extends AbstractMap to
use a tree.
WeakHashMap
Extends AbstractMap to
13
use a hash table with
weak keys.
LinkedHashMap
Extends HashMap to
14
allow insertion-order
iterations.
IdentityHashMap
Extends AbstractMap and
15 uses reference equality
when comparing
documents.
The AbstractCollection, AbstractSet, AbstractList, AbstractSequentialList and AbstractMap
classes provide skeletal implementations of the core collection interfaces, to minimize the
effort required to implement them.
The following legacy classes defined by [Link] have been discussed in the previous chapter
−
[Link].
Class & Description
Vector
This implements a
1 dynamic array. It is
similar to ArrayList, but
with some differences.
Stack
Stack is a subclass of
2 Vector that implements a
standard last-in, first-out
stack.
Dictionary
Dictionary is an abstract
class that represents a
3
key/value storage
repository and operates
much like Map.
Hashtable
Hashtable was part of the
4 original [Link] and is a
concrete implementation
of a Dictionary.
Properties
Properties is a subclass of
Hashtable. It is used to
5 maintain lists of values in
which the key is a String
and the value is also a
String.
PriorityQueue
PriorityQueue class is an
unbounded priority
queue based on a priority
6 heap. A priority queue
relying on natural
ordering also does not
permit insertion of non-
comparable objects.
BitSet
A BitSet class creates a
special type of array that
7
holds bit values. This
array can increase in size
as needed.
ArrayDeque
ArrayDeque class
provides resizable-array
and implements the
8 Deque interface. Array
deques have no capacity
restrictions so they grow
as necessary to support
usage.
EnumMap
EnumMap class is a
specialized Map
implementation for use
with enum keys. All of the
9 keys in an enum map
must come from a single
enum type that is
specified, explicitly or
implicitly, when the map
is created.
Queue
The queue interface is
provided in [Link]
package and it
implements the
10 Collection interface. The
queue implements FIFO
i.e. First In First Out. This
means that the elements
entered first are the ones
that are deleted first.
Deque
EnumMap class is a
specialized Map
implementation for use
with enum keys. All of the
11 keys in an enum map
must come from a single
enum type that is
specified, explicitly or
implicitly, when the map
is created.
Method & Description
void
bind(SocketAddress
1 bindpoint)
Binds the socket to a
local address.
void close()
2
Closes this socket.
void
connect(SocketAddress
3 endpoint)
Connects this socket to
the server.
void
connect(SocketAddress
endpoint, int timeout)
4
Connects this socket to
the server with a
specified timeout value.
SocketChannel
getChannel()
Returns the unique
5
SocketChannel object
associated with this
socket, if any.
InetAddress
getInetAddress()
6 Returns the address to
which the socket is
connected.
InputStream
getInputStream()
7
Returns an input stream
for this socket.
boolean getKeepAlive()
8 Tests if SO_KEEPALIVE is
enabled.
InetAddress
getLocalAddress()
9 Gets the local address to
which the socket is
bound.
int getLocalPort()
Returns the local port
10
number to which this
socket is bound.
SocketAddress
getLocalSocketAddress(
)
11
Returns the address of
the endpoint this socket
is bound to.
boolean getOOBInline()
12 Tests if SO_OOBINLINE is
enabled.
<T> T
getOption(SocketOptio
13 n<T> name)
Returns the value of a
socket option.
OutputStream
getOutputStream()
14
Returns an output stream
for this socket.
int getPort()
Returns the remote port
15
number to which this
socket is connected.
int
getReceiveBufferSize()
Gets the value of the
SO_RCVBUF option for
16
this Socket, that is the
buffer size used by the
platform for input on this
Socket.
SocketAddress
getRemoteSocketAddre
ss()
17 Returns the address of
the endpoint this socket
is connected to, or null if
it is unconnected.
boolean
getReuseAddress()
18
Tests if SO_REUSEADDR
is enabled.
int getSendBufferSize()
Get value of the
SO_SNDBUF option for
19 this Socket, that is the
buffer size used by the
platform for output on
this Socket.
int getSoLinger()
20 Returns setting for
SO_LINGER.
int getSoTimeout()
Returns setting for
SO_TIMEOUT. 0 returns
21
implies that the option is
disabled (i.e., timeout of
infinity).
boolean
getTcpNoDelay()
22
Tests if TCP_NODELAY is
enabled.
int getTrafficClass()
Gets traffic class or type-
23 of-service in the IP
header for packets sent
from this Socket
boolean isBound()
24 Returns the binding state
of the socket.
boolean isClosed()
25 Returns the closed state
of the socket.
boolean isConnected()
26 Returns the connection
state of the socket.
boolean
isInputShutdown()
27 Returns whether the
read-half of the socket
connection is closed.
boolean
isOutputShutdown()
28 Returns whether the
write-half of the socket
connection is closed.
void
sendUrgentData(int
29 data)
Send one byte of urgent
data on the socket.
void
setKeepAlive(boolean
30 on)
Enable/disable
SO_KEEPALIVE.
void
setOOBInline(boolean
on)
Enable/disable
SO_OOBINLINE (receipt
31
of TCP urgent data) By
default, this option is
disabled and TCP urgent
data received on a socket
is silently discarded.
<T> Socket
setOption(SocketOption
32 <T> name, T value)
Sets the value of a socket
option.
void
setPerformancePrefere
nces(int
connectionTime, int
33
latency, int bandwidth)
Sets performance
preferences for this
socket.
void
setReceiveBufferSize(in
t size)
34
Sets the SO_RCVBUF
option to the specified
value for this Socket.
void
setReuseAddress(boole
an on)
35
Enable/disable the
SO_REUSEADDR socket
option.
void
setSendBufferSize(int
size)
36
Sets the SO_SNDBUF
option to the specified
value for this Socket.
static void
setSocketImplFactory(S
ocketImplFactory fac)
37
Sets the client socket
implementation factory
for the application.
void
setSoLinger(boolean on,
int linger)
38 Enable/disable
SO_LINGER with the
specified linger time in
seconds.
void setSoTimeout(int
timeout)
39
Enable/disable
SO_TIMEOUT with the
specified timeout, in
milliseconds.
void
setTcpNoDelay(boolean
on)
40 Enable/disable
TCP_NODELAY
(disable/enable Nagle's
algorithm).
void setTrafficClass(int
tc)
Sets traffic class or type-
41
of-service octet in the IP
header for packets sent
from this Socket.
void shutdownInput()
Places the input stream
42
for this socket at "end of
stream".
void shutdownOutput()
43 Disables the output
stream for this socket.
Set<SocketOption<?>>
supportedOptions()
44 Returns a set of the
socket options supported
by this socket.
String toString()
45 Converts this socket to a
String.
Socket Client Example
The following GreetingClient is a client program that connects to a server by using a socket
and sends a greeting, and then waits for a response.
Example
package [Link];import [Link];import
[Link];import [Link];import
[Link];import [Link];import
[Link];public class GreetingClient {
public static void main(String [] args) {
String serverName = args[0];
int port = [Link](args[1]);
try {
[Link]("Connecting to " + serverName + " on port " + port);
Socket client = new Socket(serverName, port);
[Link]("Just connected to " + [Link]());
OutputStream outToServer = [Link]();
DataOutputStream out = new DataOutputStream(outToServer);
out
.writeUTF("Hello from " + [Link]());
InputStream inFromServer = [Link]();
DataInputStream in = new DataInputStream(inFromServer);
[Link]("Server says " + [Link]());
client
.close();
} catch (IOException e) {
.printStackTrace();
}}
The following GreetingServer program is an example of a server application that uses the
Socket class to listen for clients on a port number specified by a command-line argument −
package [Link];import [Link];import
[Link];import [Link];import
[Link];import [Link];import
[Link];public class GreetingServer extends Thread {
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException {
serverSocket
= new ServerSocket(port);
serverSocket
.setSoTimeout(10000);
public void run() {
while(true) {
try {
[Link]("Waiting for client on port " +
serverSocket
.getLocalPort() + "...");
Socket server = [Link]();
[Link]("Just connected to " + [Link]());
DataInputStream in = new DataInputStream([Link]());
[Link]([Link]());
DataOutputStream out = new DataOutputStream([Link]());
out
.writeUTF("Thank you for connecting to " + [Link]()
+ "\nGoodbye!");
server
.close();
} catch (SocketTimeoutException s) {
[Link]("Socket timed out!");
break;
} catch (IOException e) {
.printStackTrace();
break;
}
}
public static void main(String [] args) {
int port = [Link](args[0]);
try {
Thread t = new GreetingServer(port);
.start();
} catch (IOException e) {
.printStackTrace();
}}
Compile the client and the server and then start the server as follows −
$ java GreetingServer 6066
Waiting for client on port 6066...
Just connected to /[Link]:49462
Hello from /[Link]:49462
Waiting for client on port 6066...
Check the client program as follows −
Output
$ java GreetingClient localhost 6066
Connecting to localhost on port 6066
Just connected to localhost/[Link]:6066
Server says Thank you for connecting to /[Link]:6066
Goodbye!
The finally Block in Java
The finally block follows a try block or a catch block. A finally block of code always executes,
irrespective of occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that you want to execute,
no matter what happens in the protected code.
Syntax: Finally Block
A finally block appears at the end of the catch blocks and has the following syntax −
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
Advertisement
Points To Remember While Using Finally Block
• A catch clause cannot exist without a try statement.
• It is not compulsory to have finally clauses whenever a try/catch block is present.
• The try block cannot be present without either catch clause or finally clause.
• Any code cannot be present in between the try, catch, finally blocks.
• finally block is not executed in case exit() method is called before finally block or a fatal
error occurs in program execution.
• finally block is executed even method returns a value before finally block.
Why Java Finally Block Used?
• Java finally block can be used for clean-up (closing) the connections, files opened,
streams, etc. those must be closed before exiting the program.
• It can also be used to print some final information.
Java Finally Block Example
Here is code segment showing how to use finally after try/catch statements after handling
exception. In this example, we're creating an error accessing an element of an array using
invalid index. The catch block is handling the exception and printing the same. Now in finally
block, we're printing a statement signifying that finally block is getting executed.
package [Link];
public class ExcepTest {
public static void main(String args[]) {
int a[] = new int[2];
try {
[Link]("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Exception thrown :" + e);
}finally {
[0] = 6;
[Link]("First element value: " + a[0]);
[Link]("The finally statement is executed");
}
}
Output
Exception thrown :[Link]: 3
First element value: 6
The finally statement is executed
More Examples
Example 1
Here is code segment showing how to use finally after try/catch statements even exception is
not handled. In this example, we're creating an error accessing an element of an array using
invalid index. As the catch block is not handling the exception, we can check in output that
finally block is printing a statement signifying that finally block is getting executed.
package [Link];
public class ExcepTest {
public static void main(String args[]) {
int a[] = new int[2];
try {
[Link]("Access element three :" + a[3]);
} catch (ArithmeticException e) {
[Link]("Exception thrown :" + e);
}finally {
[0] = 6;
[Link]("First element value: " + a[0]);
[Link]("The finally statement is executed");
Output
First element value: 6
The finally statement is executed
Exception in thread "main" [Link]: 3
at [Link]([Link])
Example 2
Here is code segment showing how to use finally block where a method can return a value
within try block. In this example, we're returning a value within try block. We can check in
output that finally block is printing a statement signifying that finally block is getting executed
even after method returned a value to caller function.
package [Link];
public class ExcepTest {
public static void main(String args[]) {
[Link](testFinallyBlock());
private static int testFinallyBlock() {
int a[] = new int[2];
try {
return 1;
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Exception thrown :" + e);
}finally {
[0] = 6;
[Link]("First element value: " + a[0]);
[Link]("The finally statement is executed");
return 0;
Output
First element value: 6
The finally statement is executed
1