Notes of Java Unit 4
Notes of Java Unit 4
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.
Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a
stream because it is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with
the console.
Let's see the code to print output and an error message to the console.
Let's see the code to print output and an error message to the console.
1. System.out.println("simple message");
2. System.err.println("error message");
OutputStream vs InputStream
The explanation of OutputStream and InputStream classes are given below:
OutputStream
Java application uses an output stream to write data to a destination; it may be a file, an
array, peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source; it may be a file, an
array, peripheral device or socket.
Let's understand the working of Java OutputStream and InputStream by the figure given
below.
OutputStream class
OutputStream class is an abstract class. It is the superclass of all classes representing an
output stream of bytes. An output stream accepts output bytes and sends them to some
sink.
Method Description
1) public void write(int)throws IOException is used to write a byte to the current output stream.
2) public void write(byte[])throws is used to write an array of byte to the current outpu
IOException stream.
4) public void close()throws IOException is used to close the current output stream.
Signature
The signature of Stream filter() method is given below:
Parameter
predicate: It takes Predicate reference as an argument. Predicate is a functional
interface. So, you can also pass lambda expression here.
Return
It returns a new stream.
1. import java.util.*;
2. class Product{
3. int id;
4. String name;
5. float price;
6. public Product(int id, String name, float price) {
7. this.id = id;
8. this.name = name;
9. this.price = price;
10. }
11. }
12. public class JavaStreamExample {
13. public static void main(String[] args) {
14. List<Product> productsList = new ArrayList<Product>();
15. //Adding Products
16. productsList.add(new Product(1,"HP Laptop",25000f));
17. productsList.add(new Product(2,"Dell Laptop",30000f));
18. productsList.add(new Product(3,"Lenevo Laptop",28000f));
19. productsList.add(new Product(4,"Sony Laptop",28000f));
20. productsList.add(new Product(5,"Apple Laptop",90000f));
21. productsList.stream()
22. .filter(p ->p.price> 30000) // filtering price
23. .map(pm ->pm.price) // fetching price
24. .forEach(System.out::println); // iterating price
25. }
26. }
Output:
90000.0
Java BufferedOutputStream Class
Java BufferedOutputStream class is used for buffering an output stream. It internally
uses buffer to store data. It adds more efficiency than to write data directly into a
stream. So, it makes the performance fast.
For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see
the syntax for adding the buffer in an OutputStream:
Constructor Description
BufferedOutputStream(OutputStream os) It creates the new buffered output stream which is used for writin
the data to the specified output stream.
BufferedOutputStream(OutputStream os, It creates the new buffered output stream which is used for writin
int size) the data to the specified output stream with a specified buffer siz
Java BufferedOutputStream class methods
Method Description
void write(int b) It writes the specified byte to the buffered output stream.
void write(byte[] b, int It write the bytes from the specified byte-input stream into a specifie
off, int len) byte array, starting with the given offset
1. package com.javatpoint;
2. import java.io.*;
3. public class BufferedOutputStreamExample{
4. public static void main(String args[])throws Exception{
5. FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
6. BufferedOutputStream bout=new BufferedOutputStream(fout);
7. String s="Welcome to javaTpoint.";
8. byte b[]=s.getBytes();
9. bout.write(b);
10. bout.flush();
11. bout.close();
12. fout.close();
13. System.out.println("success");
14. }
15. }
Output:
Success
testout.txt
Java - RandomAccessFile
This class is used for reading and writing to random access file. A random access file
behaves like a large array of bytes. There is a cursor implied to the array called
file pointer, by moving the cursor we do the read write operations. If end-of-file is
reached before the desired number of byte has been read than EOFException is thrown.
It is a type of IOException.
Constructor
Constructor Description
RandomAccessFile(File Creates a random access file stream to read from, and optionall
file, String mode) to write to, the file specified by the File argument.
RandomAccessFile(String name, Creates a random access file stream to read from, and optionall
String mode) to write to, a file with the specified name.
Method
void close() It closes this random access file stream and releases any system
resources associated with the stream.
FileChannel getChannel() It returns the unique FileChannel object associated with this fil
void seek(long pos) It sets the file-pointer offset, measured from the beginning o
this file, at which the next read or write occurs.
void writeFloat(float v) It converts the float argument to an int using the floatToIntBit
method in class Float, and then writes that int value to the fil
as a four-byte quantity, high byte first.
void seek(long pos) It sets the file-pointer offset, measured from the beginning o
this file, at which the next read or write occurs.
Example
1. import java.io.IOException;
2. import java.io.RandomAccessFile;
3.
4. public class RandomAccessFileExample {
5. static final String FILEPATH ="myFile.TXT";
6. public static void main(String[] args) {
7. try {
8. System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
9. writeToFile(FILEPATH, "I love my country and my people", 31);
10. } catch (IOException e) {
11. e.printStackTrace();
12. }
13. }
14. private static byte[] readFromFile(String filePath, int position, int size)
15. throws IOException {
16. RandomAccessFile file = new RandomAccessFile(filePath, "r");
17. file.seek(position);
18. byte[] bytes = new byte[size];
19. file.read(bytes);
20. file.close();
21. return bytes;
22. }
23. private static void writeToFile(String filePath, String data, int position)
24. throws IOException {
25. RandomAccessFile file = new RandomAccessFile(filePath, "rw");
26. file.seek(position);
27. file.write(data.getBytes());
28. file.close();
29. }
30. }
The myFile.TXT contains text "This class is used for reading and writing to random access
file."
The forName() method of Class class is used to register the driver class. This method is used
dynamically load the driver class.
1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");
1. con.close();
We must have to implement the Serializable interface for serializing the object.
The Serializable interface must be implemented by the class whose object needs to be
persisted.
The String class and all the wrapper classes implement the java.io.Serializable interface
by default.
Student.java
1. import java.io.Serializable;
2. public class Student implements Serializable{
3. int id;
4. String name;
5. public Student(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }
In the above example, Student class implements Serializable interface. Now its objects
can be converted into stream. The main class implementation of is showed in the next
code.
ObjectOutputStream class
The ObjectOutputStream class is used to write primitive data types, and Java objects to
an OutputStream. Only objects that support the java.io.Serializable interface can be
written to streams.
Constructor
Method Description
1) public final void writeObject(Object obj) throws It writes the specified object to th
IOException {} ObjectOutputStream.
2) public void flush() throws IOException {} It flushes the current output stream.
3) public void close() throws IOException {} It closes the current output stream.
ObjectInputStream class
An ObjectInputStream deserializes objects and primitive data written using an
ObjectOutputStream.
Constructor
Method Description
1) public final Object readObject() throws IOException, It reads an object from the input stream.
ClassNotFoundException{}
1. import java.io.*;
2. class Persist{
3. public static void main(String args[]){
4. try{
5. //Creating the object
6. Student s1 =new Student(211,"ravi");
7. //Creating stream and writing the object
8. FileOutputStream fout=new FileOutputStream("f.txt");
9. ObjectOutputStream out=new ObjectOutputStream(fout);
10. out.writeObject(s1);
11. out.flush();
12. //closing the stream
13. out.close();
14. System.out.println("success");
15. }catch(Exception e){System.out.println(e);}
16. }
17. }
Output:
Success
Deserialization is the process of reconstructing the object from the serialized state. It is
the reverse operation of serialization. Let's see an example where we are reading the
data from a deserialized object.
1. import java.io.*;
2. class Depersist{
3. public static void main(String args[]){
4. try{
5. //Creating stream to read the object
6. ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
7. Student s=(Student)in.readObject();
8. //printing the data of the serialized object
9. System.out.println(s.id+" "+s.name);
10. //closing the stream
11. in.close();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }
OUTPUT:-
211 Ravi
1. import java.io.Serializable;
2. class Person implements Serializable{
3. int id;
4. String name;
5. Person(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }
10. class Student extends Person{
11. String course;
12. int fee;
13. public Student(int id, String name, String course, int fee) {
14. super(id,name);
15. this.course=course;
16. this.fee=fee;
17. }
18. }
19. public class SerializeISA
20. {
21. public static void main(String args[])
22. {
23. try{
24. //Creating the object
25. Student s1 =new Student(211,"ravi","Engineering",50000);
26. //Creating stream and writing the object
27. FileOutputStream fout=new FileOutputStream("f.txt");
28. ObjectOutputStream out=new ObjectOutputStream(fout);
29. out.writeObject(s1);
30. out.flush();
31. //closing the stream
32. out.close();
33. System.out.println("success");
34. }catch(Exception e){System.out.println(e);}
35. try{
36. //Creating stream to read the object
37. ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
38. Student s=(Student)in.readObject();
39. //printing the data of the serialized object
40. System.out.println(s.id+" "+s.name+" "+s.course+" "+s.fee);
41. //closing the stream
42. in.close();
43. }catch(Exception e){System.out.println(e);}
44. }
45. }
Output:
success
211 ravi Engineering 50000
success
Methods
Method Description
bind(SocketAddress bindpoint) This method binds the given socket to the specified loca
address.
close() This method closes the socket.
connect(SocketAddress endpoint) The connect() method connects this socket to the serve
connect(SocketAddress endpoint, This method connects this socket to the server with a specifie
int timeout) timeout value.
getLocalAddress() It returns the local address to which the given socket is bound.
getLocalPort() It gets the local port number to which the specified socket
bound.
getOutputStream() This method returns an output stream for the specified socket.
getPort() This method returns the remote port number to which the socke
is connected.
getReceiveBufferSize() It returns the value of the SO_RCVBUF option for this Socket.
getRemoteSocketAddress() This method either returns the address of the endpoint to whic
this socket is connected or it returns null if the socket
unconnected.
getSendBufferSize() This method gets the value of the SO_SNDBUF option for th
Socket.
getSoLinger() This method returns setting for the SO_LINGER option.
sendUrgentData(int data) This method sends one byte of urgent data on the socket.
setReceiveBufferSize(int size) This method returns the SO_RCVBUF option to the specifie
value for this Socket.
setSendBufferSize(int size) This method returns the SO_SNDBUF option to the specifie
value for this Socket.
setSoLinger(boolean on, int linger) It enables or disables the SO_LINGER option with the specifie
linger time in seconds.
setSoTimeout(int timeout) This method enables or disables the SO_TIMEOUT option wit
the specified time in milliseconds.
setTrafficClass(int tc) It returns the traffic class or type-of-service octet in the IP heade
for packets sent from the Socket.
shutdownInput() This method places the input stream for this socket at the end o
this stream.
shutdownOutput() This method disables the output stream for this socket.
Example 1
1. import java.io.IOException;
2. import java.net.*;
3. public class JavaSocketExample1 {
4. public static void main(String[] args) throws IOException {
5. Socket socket = new Socket();
6. InetAddress inetAddress=InetAddress.getByName("localhost");
7. //the port should be greater or equal to 0, else it will throw an error
8. int port=1085;
9. //calling the constructor of the SocketAddress class
10. SocketAddress socketAddress=new InetSocketAddress(inetAddress, port);
11. //binding the socket with the inetAddress and port number
12. socket.bind(socketAddress);
13. //connect() method connects the specified socket to the server
14. socket.connect(socketAddress);
15. //setSendBufferSize() sets the send buffer size or SO_SNDBUF option with the speci
fied value
16. socket.setSendBufferSize(67);
17. //getSendBufferSize() method returns the buffer size(SO_SNDBUF) used by the plat
form for output
18. System.out.println("Send Buffer size: "+socket.getSendBufferSize());
19. //enabling the boolean value true
20. boolean on=false;
21. //setKeepAlive() method either enables or disables the SO_KEEPALIVE option
22. socket.setKeepAlive(on);
23. //getKeepAlive() returns a boolean indicating whether SO_KEEPALIVE option is ena
bled or not
24. if(socket.getKeepAlive()){
25. System.out.println("SO_KEEPALIVE option is enabled");
26. }
27. else{
28. System.out.println("SO_KEEPALIVE option is disabled");
29. }
30. //getRemoteSocketAddress() returns the address of the endpoint of the specified s
ocket if the socket is connected
31. System.out.println("Remote socket address: "+socket.getRemoteSocketAddress());
32. }
33. }
OUTPUT:--
The source files for the Callback sample application are located in the WLEdir\samples\
corba\callback_java directory of the BEA WebLogic Enterprise software. See "Building and
Running the Callback Sample Application"" for more information.
The RMI provides remote communication between the applications using two
objects stub and skeleton.
A remote object is an object whose method can be invoked from another JVM. Let's
understand the stub and skeleton objects:
stub
The stub is an object, acts as a gateway for the client side. All the outgoing requests are
routed through it. It resides at the client side and represents the remote object. When
the caller invokes method on the stub object, it does the following tasks:
1. It initiates a connection with remote Virtual Machine (JVM),
2. It writes and transmits (marshals) the parameters to the remote Virtual Machine
(JVM),
3. It waits for the result
4. It reads (unmarshals) the return value or exception, and
5. It finally, returns the value to the caller.
skeleton
The skeleton is an object, acts as a gateway for the server side object. All the incoming
requests are routed through it. When the skeleton receives the incoming request, it does
the following tasks:
In the Java 2 SDK, an stub protocol was introduced that eliminates the need for
skeletons.
Understanding requirements for the
distributed applications
If any application performs these tasks, it can be distributed application.
.
1. The application need to locate the remote method
2. It need to provide the communication with the remote objects, and
3. The application need to load the class definitions for the objects.
The RMI application have all these features, so it is called the distributed application.
RMI Example
In this example, we have followed all the 6 steps to create and run the rmi application.
The client application need only two files, remote interface and client application. In the
rmi application, both client and server interacts with the remote interface. The client
application invokes methods on the proxy object, RMI sends the request to the remote
JVM. The return value is sent back to the proxy object and then to the client application.
1) create the remote interface
For creating the remote interface, extend the Remote interface and declare the
RemoteException with all the methods of the remote interface. Here, we are creating a
remote interface that extends the Remote interface. There is only one method named
add() and it declares RemoteException.
1. import java.rmi.*;
2. public interface Adder extends Remote{
3. public int add(int x,int y)throws RemoteException;
4. }
Most native methods are written in C. The mechanism used to integrate C code with
a Java program is called the Java Native Interface (JNI). This methodology was
created by Java 1.1 and then expanded and enhanced by Java 2. (Java 1.0 used a
different approach, which is now completely outdated.) A detailed description of the
JNI is beyond the scope of this book, but the following description provides sufficient
information for most applications.
Note: The precise steps that you need to follow will vary between different Java
environments and versions. This also depends on the language that you are using to
implement the native method. The following discussion assumes a Windows
95/98/NT environment. The language used to implement the native method is C.
The easiest way to understand the process is to work through an example. To begin,
enter the following short program, which uses a native method called test( ):
The library is loaded by the loadLibrary( ) method, which is part of the System class. This is
its general form:
Collections in Java
The Collection in Java is a framework that provides an architecture to store and
manipulate the group of objects.
Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
The Collection framework represents a unified architecture for storing and manipulating
a group of objects. It has:
No Method Description
.
5 default boolean removeIf(Predicate<? It is used to delete all the elements of the collectio
super E> filter) that satisfy the specified predicate.
13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the runtime typ
of the returned array is that of the specified array.
15 default Stream<E> parallelStream() It returns a possibly parallel Stream with the collectio
as its source.
Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.
There are only three methods in the Iterator interface. They are:
No Method Description
.
1 public boolean It returns true if the iterator has more elements otherwise it return
hasNext() false.
2 public Object next() It returns the element and moves the cursor pointer to the nex
element.
3 public void remove() It removes the last elements returned by the iterator. It is less used.
Java Vector
Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can
store n-number of elements in it as there is no size limit. It is a part of Java Collection
framework since Java 1.2. It is found in the java.util package and implements
the List interface, so we can use all the methods of List interface here.
It is recommended to use the Vector class in the thread-safe implementation only. If you
don't need to use the thread-safe implementation, you should use the ArrayList, the
ArrayList will perform better in such case.
The Iterators returned by the Vector class are fail-fast. In case of concurrent
modification, it fails and throws the ConcurrentModificationException.
It is similar to the ArrayList, but with two differences-
o Vector is synchronized.
o Java Vector contains many legacy methods that are not the part of a collections
framework.
S Constructor Description
N
3) vector(int initialCapacity, int It constructs an empty vector with the specified initia
capacityIncrement) capacity and capacity increment.
4) Vector( Collection<? extends E> It constructs a vector that contains the elements of
c) collection c.
Points to remember
o A Hashtable is an array of a list. Each list is known as a bucket. The position of the
bucket is identified by calling the hashcode() method. A Hashtable contains
values based on the key.
o Java Hashtable class contains unique elements.
o Java Hashtable class doesn't allow null key or value.
o Java Hashtable class is synchronized.
o The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.
Constructor Description
Hashtable() It creates an empty hashtable having the initial default capacity and loa
factor.
Hashtable(int capacity) It accepts an integer parameter and creates a hash table that contains
specified initial capacity.
Hashtable(int capacity, float It is used to create a hash table having the specified initial capacity an
loadFactor) loadFactor.
Hashtable(Map<? extends K,? It creates a new hash table wiith the same mappings as the given Map.
extends V> t)
Method Description
V compute(K key, BiFunction<? super K,? It is used to compute a mapping for the specified key an
super V,? extends V> its current mapped value (or null if there is no curren
remappingFunction) mapping).
V computeIfAbsent(K key, Function<? It is used to compute its value using the given mappin
super K,? extends V> mappingFunction) function, if the specified key is not already associated wit
a value (or is mapped to null), and enters it into this ma
unless null.
V computeIfPresent(K key, BiFunction<? It is used to compute a new mapping given the key and it
super K,? super V,? extends V> current mapped value if the value for the specified key
remappingFunction) present and non-null.
boolean equals(Object o) It is used to compare the specified Object with the Map.
void forEach(BiConsumer<? super K,? It performs the given action for each entry in the map unt
super V> action) all entries have been processed or the action throws a
exception.
V getOrDefault(Object key, V It returns the value to which the specified key is mapped
defaultValue) or defaultValue if the map contains no mapping for th
key.
int hashCode() It returns the hash code value for the Map
Set<K> keySet() It returns a Set view of the keys contained in the map.
V merge(K key, V value, BiFunction<? If the specified key is not already associated with a valu
super V,? super V,? extends V> or is associated with null, associates it with the given non
remappingFunction) null value.
V put(K key, V value) It inserts the specified value with the specified key in th
hash table.
void putAll(Map<? extends K,? extends It is used to copy all the key-value pair from map t
V> t)) hashtable.
V putIfAbsent(K key, V value) If the specified key is not already associated with a valu
(or is mapped to null) associates it with the given valu
and returns null, else returns the current value.
boolean remove(Object key, Object It removes the specified values with the associate
value) specified keys from the hashtable.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V It replaces the old value with the new value for a specifie
newValue) key.
void replaceAll(BiFunction<? super K,? It replaces each entry's value with the result of invokin
super V,? extends V> function) the given function on that entry until all entries have bee
processed or the function throws an exception.
boolean contains(Object value) This method returns true if some value equal to the valu
exists within the hash table, else return false.
boolean containsValue(Object value) This method returns true if some value equal to the valu
exists within the hash table, else return false.
boolean containsKey(Object key) This method return true if some key equal to the key exist
within the hash table, else return false.
boolean isEmpty() This method returns true if the hash table is empt
returns false if it contains at least one key.
protected void rehash() It is used to increase the size of the hash table an
rehashes all of its keys.
V get(Object key) This method returns the object that contains the valu
associated with the key.
V remove(Object key) It is used to remove the key and its value. This metho
returns the value associated with the key.
int size() This method returns the number of entries in the has
table.
Java 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). Java collection framework provides many interfaces
and classes to store the collection of objects. One of them is the Stack class that
provides different operations such as push, pop, search, etc.
In this section, we will discuss the Java Stack class, its methods, and implement the
stack data structure in a Java program. But before moving to the Java Stack class have a
quick view of how the stack works.
The stack data structure has the two most important operations that are push and pop.
The push operation inserts an element into the stack and pop operation removes an
element from the top of the stack. Let's see how they work on stack.
Let's push 20, 13, 89, 90, 11, 45, 18, respectively into the stack.
Java Enums
The Enum in Java is a data type which contains a fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, and SATURDAY) , directions (NORTH, SOUTH, EAST, and WEST),
season (SPRING, SUMMER, WINTER, and AUTUMN or FALL), colors (RED, YELLOW, BLUE,
GREEN, WHITE, and BLACK) etc. According to the Java naming conventions, we should
have all constants in capital letters. So, we have enum constants in capital letters.
Java Enums can be thought of as classes which have a fixed set of constants (a variable
that does not change). The Java enum constants are static and final implicitly. It is
available since JDK 1.5.
Enums are used to create our own data type like classes. The enum data type (also
known as Enumerated Data Type) is used to define an enum in Java. Unlike C/C++,
enum in Java is more powerful. Here, we can define an enum either inside the class or
outside the class.
Java Enum internally inherits the Enum class, so it cannot inherit any other class, but it
can implement many interfaces. We can have fields, constructors, methods, and main
methods in Java enum.
Output:
Winter
Spring
Summer
Fall
Set in Java
The set is an interface available in the java.util package. The set interface extends the
Collection interface. An unordered collection or list in which duplicates are not allowed
is referred to as a collection interface. The set interface is used to create the
mathematical set. The set interface use collection interface's methods to avoid the
insertion of the same elements. SortedSet and NavigableSet are two interfaces that
extend the set implementation.
In the above diagram, the NavigableSet and SortedSet are both the interfaces.
The NavigableSet extends the SortedSet, so it will not retain the insertion order and store the
data in a sorted way.
SetExample1.java
1. import java.util.*;
2. public class setExample{
3. public static void main(String[] args)
4. {
5. // creating LinkedHashSet using the Set
6. Set<String> data = new LinkedHashSet<String>();
7.
8. data.add("JavaTpoint");
9. data.add("Set");
10. data.add("Example");
11. data.add("Set");
12.
13. System.out.println(data);
14. }
15. }
Output:
Java List
List in Java provides the facility to maintain the ordered collection. It contains the index-
based methods to insert, update, delete and search the elements. It can have the
duplicate elements also. We can also store the null elements in the list.
The List interface is found in the java.util package and inherits the Collection interface. It
is a factory of ListIterator interface. Through the ListIterator, we can iterate the list in
forward and backward directions. The implementation classes of List interface
are ArrayList, LinkedList, Stack and Vector. The ArrayList and LinkedList are widely used
in Java programming. The Vector class is deprecated since Java 5.
Method Description
void add(int index, E element) It is used to insert the specified element at the specified position in
a list.
boolean add(E e) It is used to append the specified element at the end of a list.
boolean addAll(Collection<? extends It is used to append all of the elements in the specified collection
E> c) to the end of a list.
boolean addAll(int index, Collection<? It is used to append all the elements in the specified collection,
extends E> c) starting at the specified position of the list.
void clear() It is used to remove all of the elements from this list.
boolean equals(Object o) It is used to compare the specified object with the elements of a
list.
int hashcode() It is used to return the hash code value for a list.
E get(int index) It is used to fetch the element from the particular position of the
list.
Object[] toArray() It is used to return an array containing all of the elements in this
list in the correct order.
<T> T[] toArray(T[] a) It is used to return an array containing all of the elements in this
list in the correct order.
boolean contains(Object o) It returns true if the list contains the specified element
boolean containsAll(Collection<?> c) It returns true if the list contains all the specified element
int indexOf(Object o) It is used to return the index in this list of the first occurrence of
the specified element, or -1 if the List does not contain this
element.
E remove(int index) It is used to remove the element present at the specified position
in the list.
boolean remove(Object o) It is used to remove the first occurrence of the specified element.
boolean removeAll(Collection<?> c) It is used to remove all the elements from the list.
void replaceAll(UnaryOperator<E> It is used to replace all the elements from the list with the specified
operator) element.
void retainAll(Collection<?> c) It is used to retain all the elements in the list that are present in the
specified collection.
E set(int index, E element) It is used to replace the specified element in the list, present at the
specified position.
void sort(Comparator<? super E> c) It is used to sort the elements of the list on the basis of specified
comparator.
Spliterator<E> spliterator() It is used to create spliterator over the elements in a list.
List<E> subList(int fromIndex, int It is used to fetch all the elements lies within the given range.
toIndex)
int size() It is used to return the number of elements present in the list.
A Map is useful if you have to search, update or delete elements on the basis of a key.
Class Description
HashMap HashMap is the implementation of Map, but it doesn't maintain any order.
Iterator in Java
In Java, an Iterator is one of the Java cursors. Java Iterator is an interface that is
practiced in order to iterate over a collection of Java object components entirety one by
one. It is free to use in the Java programming language since the Java 1.2 Collection
framework. It belongs to java.util package.
Though Java Iterator was introduced in Java 1.2, however, it is still not the oldest tool
available to traverse through the elements of the Collection object. The oldest Iterator in
the Java programming language is the Enumerator predated Iterator. Java Iterator
interface succeeds the enumerator iterator that was practiced in the beginning to
traverse over some accessible collections like the ArrayLists.
The Java Iterator is also known as the universal cursor of Java as it is appropriate for all
the classes of the Collection framework. The Java Iterator also helps in the operations
like READ and REMOVE. When we compare the Java Iterator interface with the
enumeration iterator interface, we can say that the names of the methods available in
Java Iterator are more precise and straightforward to use.
o The user can apply these iterators to any of the classes of the Collection
framework.
o In Java Iterator, we can use both of the read and remove operations.
o If a user is working with a for loop, they cannot modernize(add/remove) the
Collection, whereas, if they use the Java Iterator, they can simply update the
Collection.
o The Java Iterator is considered the Universal Cursor for the Collection API.
o The method names in the Java Iterator are very easy and are very simple to use.
o The Java Iterator only preserves the iteration in the forward direction. In simple
words, the Java Iterator is a uni-directional Iterator.
o The replacement and extension of a new component are not approved by the
Java Iterator.
o In CRUD Operations, the Java Iterator does not hold the various operations like
CREATE and UPDATE.
o In comparison with the Spliterator, Java Iterator does not support traversing
elements in the parallel pattern which implies that Java Iterator supports only
Sequential iteration.
o In comparison with the Spliterator, Java Iterator does not support more reliable
execution to traverse the bulk volume of data.
If the user modifies the underlying collection while traversing over an Iterator leading to
that collection, then the Iterator will typically acknowledge it and will throw an exception
in the next time when the user will attempt to get the next component from the Iterator.
Java Iterator Methods
The following figure perfectly displays the class diagram of the Java Iterator interface. It
contains a total of four methods that are:
o hasNext()
o next()
o remove()
o forEachRemaining()
The forEachRemaining() method was added in the Java 8. Let's discuss each method in
detail.
o boolean hasNext(): The method does not accept any parameter. It returns true if
there are more elements left in the iteration. If there are no more elements left,
then it will return false.
If there are no more elements left in the iteration, then there is no need to call
the next() method. In simple words, we can say that the method is used to
determine whether the next() method is to be called or not.
o E next(): It is similar to hasNext() method. It also does not accept any parameter.
It returns E, i.e., the next element in the traversal. If the iteration or collection of
objects has no more elements left to iterate, then it throws the
NoSuchElementException.
o default void remove(): This method also does not require any parameters. There
is no return type of this method. The main function of this method is to remove
the last element returned by the iterator traversing through the underlying
collection. The remove () method can be requested hardly once per the next ()
method call. If the iterator does not support the remove operation, then it throws
the UnSupportedOperationException. It also throws the IllegalStateException if
the next method is not yet called.
o default void forEachRemaining(Consumer action): It is the only method of
Java Iterator that takes a parameter. It accepts action as a parameter. Action is
nothing but that is to be performed. There is no return type of the method. This
method performs the particularized operation on all of the left components of
the collection until all the components are consumed or the action throws an
exception. Exceptions thrown by action are delivered to the caller. If the action is
null, then it throws a NullPointerException.