Friday, June 22, 2018

How HashMap put and get operations works in JAVA

Put operation

The put operation performs the following steps :
1. calculate hashcode for key
2. rehash it. lets call the rehashed results as h
3. calculate bucket index as h & (capacity -1)
4. now iterate over the bucket and compare key with all existing keys using equals()
5. if the key already exists, change the value of that Entry object
6. else create a new Entry object and add to the head of the linked list
7. increment mod count
8. resize if necessary

get operation

The get operation performs the following steps :
1. calculate hashcode for key
2. rehash it. lets call the rehashed results as h
3. calculate bucket index as h & (capacity -1)
4. now iterate over the bucket and compare key with all existing keys using equals()
5. if the key already exists return the corresponding value in the Entry object

Difference Between executeQuery() Vs executeUpdate() Vs execute() In JDBC

ResultSet executeQuery(String sql) throws SQLException :

This method is used for SQL statements which retrieve some data from the database. For example is SELECTstatement. This method is meant to be used for select queries which fetch some data from the database. This method returns one java.sql.ResultSet object which contains the data returned by the query.

int executeUpdate(String sql) throws SQLException :

This method is used for SQL statements which update the database in some way. For example INSERTUPDATE and DELETE statements. All these statements are DML(Data Manipulation Language) statements. This method can also be used for DDL(Data Definition Language) statements which return nothing. For example CREATE and ALTER statements. This method returns an int value which represents the number of rows affected by the query. This value will be 0 for the statements which return nothing.

boolean execute(String sql) throws SQLException :

This method can be used for all types of SQL statements. If you don’t know which method to use for you SQL statements, then this method can be the best option. This method returns a boolean value. TRUE indicates that statement has returned a ResultSet object and FALSE indicates that statement has returned an int value or returned nothing.