Category Archives: Class

Java: HashMap Class Methods and Examples


java.util.HashMap class inherits AbstractMap class and implements the Map interface. HashMap values store on the basis of key and value pair where each pair is known as an Entry.

  • K: It’s the type of Key in HashMap
  • V: It’s a type of value with respect to Key.

HashMap Class Declaration


public class HashMap extends implements Map, Cloneable, Serializable  

See Also:

Points to Remember:

  • HashMap uses data structure as a Hash Table.
  • HashMap store values based on keys.
  • HashMap contains unique keys.
  • HashMap allows duplicate values.
  • HashMap doesn’t maintain order.
  • HashMap class allows only one null key and multiple null values.
  • HashMap is not synchronized.
  • HashMap initial default capacity is 16 elements with a load factor of 0.75.

HashMap Representataion

Difference between HashSet and HashMap

HashSet Class contains only values whereas HashMap Class contains an entry (key and value pair).

HashMap Class Constructors

Constructor Description
HashMap() It is used to construct a default HashMap.
HashMap(Map m) It is used to initialize the hash map by using the elements of the given Map object m.
HashMap(int capacity) It is used to initializes the capacity of the hash map to the given integer value, capacity.
HashMap(int capacity, float loadFactor) It is used to initialize both the capacity and load factor of the hash map by using its arguments.

HashMap Class Methods

Method Description
void clear() Use to remove all of the mappings from this map.
boolean isEmpty() Use to return true if this map contains no key-value mappings.
Object clone() Use to return a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
Set entrySet() Use to return a collection view of the mappings contained in this map.
Set keySet() Use to return a set view of the keys contained in this map.
V put(Object key, Object value) Use to insert an entry in the map.
void putAll(Map map) Use to insert the specified map in the map.
V putIfAbsent(K key, V value) It inserts the specified value in the map only when  specified key is not already specified.
V remove(Object key) Use to delete an entry for the specified key.
boolean remove(Object key, Object value) removes the  values with the associated specified keys from the map.
V compute(K key, BiFunction remappingFunction) Use to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
V computeIfAbsent(K key, Function mappingFunction) Use to compute its value using the given mapping function, if the specified key is not mapped with a value or null, and enters it into this map unless null.
V computeIfPresent(K key, BiFunction remappingFunction) Use to compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null.
boolean containsValue(Object value) It returns true if some value equal to the value exists within the map, else return false.
boolean containsKey(Object key) It returns true if some key equal to the key exists within the map, else return false.
boolean equals(Object o) Use to compare the specified Object with the Map.
void forEach(BiConsumer action) Added in Java 8 to  performs the given action for each entry in the map  or the action throws an exception.
V get(Object key) This method returns the object that contains the value associated with respect to key.
V getOrDefault(Object key, V defaultValue) Added in Java 8. It returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key.
boolean isEmpty() It returns true if the map is empty; returns false if it contains at least one key.
V merge(K key, V value, BiFunction remappingFunction) If the specified key is not already associated with a value or is associated with null then associates it with the given non-null value.
V replace(K key, V value) It replaces the specified value with respect to specified key.
boolean replace(K key, V oldValue, V newValue) Replaces the old value with the new value with respect to specified key.
void replaceAll(BiFunction function) It replaces each entry’s value with entry until all entries have been processed or the function throws an exception.
Collection values() It returns a collection of the values contained in the map.
int size() It returns the count of number of entries in the map.

Example: add elements

Here, you will learn different ways to insert elements.

import java.util.*;

class HashMapExample1 {
	public static void main(String args[]) {
		HashMap<Integer,String> hm = new HashMap<Integer,String>();
		System.out.println("Initial hash map elements: " + hm );
		hm.put(20, "Anuj");
		hm.put(21, "Virendra");
		hm.put(22, "Raghav");

		System.out.println("\nAfter invoking put() method");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}

		hm.putIfAbsent(23, "Gaurav");
		System.out.println("\nAfter invoking putIfAbsent() method");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
		HashMap map = new HashMap();
		map.put(24, "Ravi");
		map.putAll(hm);
		System.out.println("\nAfter invoking putAll() method ");
		for (Map.Entry m : map.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
	}
}

Output :


Initial hash map elements: {}

After invoking put() method
20 Anuj
21 Virendra
22 Raghav

After invoking putIfAbsent() method
20 Anuj
21 Virendra
22 Raghav
23 Gaurav

After invoking putAll() method 
20 Anuj
21 Virendra
22 Raghav
23 Gaurav
24 Ravi

HashMap Example : remove()

Here you will see different ways to remove elements from HashMap

import java.util.*;
import java.util.HashMap;

public class HashMapExample2 {
	public static void main(String args[]) {
		HashMap<Integer,String> map = new HashMap<Integer,String>();
map.put(20, "Anuj");
		map.put(21, "Virendra");
		map.put(22, "Raghav");
		map.put(23, "Gaurav");
		System.out.println("Initial hash map elements: " + map);
		// key-based removal
		map.remove(20);
		System.out.println("\nUpdated hash map  elements: " + map);
		// value-based removal
		map.remove(21);
		System.out.println("\nUpdated hash map  elements: " + map);
		// key-value pair based removal
		map.remove(22, "Raghav");
		System.out.println("\nUpdated hash map  elements: " + map);
	}
}

Output :


Initial hash map elements: {20=Anuj, 21=Virendra, 22=Raghav, 23=Gaurav}

Updated hash map  elements: {21=Virendra, 22=Raghav, 23=Gaurav}

Updated hash map  elements: {22=Raghav, 23=Gaurav}

Updated hash map  elements: {23=Gaurav}

HashMap Example : replace()

Here you will see different ways to replace() elements in HashMap

import java.util.*;

class HashMapExample3 {
	public static void main(String args[]) {
		HashMap<Integer,String> hm = new HashMap<Integer,String>();
		hm.put(20, "Anuj");
		hm.put(21, "Virendra");
		hm.put(22, "Raghav");
		System.out.println("Initial hash map elements:");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
		System.out.println("\nUpdated hash map elements:");
		hm.replace(22, "Gaurav");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
		System.out.println("\nUpdated hash map elements:");
		hm.replace(21, "Virendra", "Ravi");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
		System.out.println("\nUpdated hash map elements:");
		hm.replaceAll((k, v) -> "Anuj");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
	}
}

Output :


Initial hash map elements:
20 Anuj
21 Virendra
22 Raghav

Updated hash map elements:
20 Anuj
21 Virendra
22 Gaurav

Updated hash map elements:
20 Anuj
21 Ravi
22 Gaurav

Updated hash map elements:
20 Anuj
21 Anuj
22 Anuj

HashMap Example: Objects handling

import java.util.*;
public class Magzine {
	int id;
	String name,author,publisher;
	int quantity;
	public Magzine(int id, String name, String author, String publisher, int quantity) {
	    this.id = id;
	    this.name = name;
	    this.author = author;
	    this.publisher = publisher;
	    this.quantity = quantity;
	}    

}
public class MapExample {
import java.util.HashMap;
import java.util.Map;

public class HashMapWithObjectsExample {

	public static void main(String[] args) {
	    //Creating map of Magzines
	    Map<Integer,Magzine> map=new HashMap<Integer,Magzine>();
	    //Creating Books
	    Magzine m1=new Magzine(21,"The Sun","Sy Sunfranchy","The Sun Company",8);
	    Magzine m2=new Magzine(22,"Glimmer Trains","Unknown","Glimmer Train Press",4);
	    Magzine m3=new Magzine(23,"Crazy horse","Brett Lot","College of Charleston",6);
	    //Adding Magzines to map
	    map.put(1,m1);
	    map.put(2,m2);
	    map.put(3,m3);  

	    //Traversing map
	    for(Map.Entry<Integer,Magzine> entry:map.entrySet()){
	        int key=entry.getKey();
	        Magzine m=entry.getValue();
	        System.out.println("\nMagzine "+key+" Details:");
	        System.out.println(m.id+" "+m.name+" "+m.author+" "+m.publisher+" "+m.quantity);
	    }
	}
}

Output :



Magzine 1 Details:
21 The Sun Sy Sunfranchy The Sun Company 8

Magzine 2 Details:
22 Glimmer Trains Unknown Glimmer Train Press 4

Magzine 3 Details:
23 Crazy horse Brett Lot College of Charleston 6

References

Advertisements

Java : java.lang.Object Class & Methods


java.lang.Object  is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class. It’s also called as Object Class.

Methods of Object Class

Below are methods of Object Class for different purpose  as below:

  1. protected Object clone() : Creates and return copy of this object.
  2. boolean equals(Object obj) : Indicate weather other object is equal or not.
  3. protected void finalize() : To make object finalize for garbage collection.
  4. Class getClass() : Returns the runtime class of this Object.
  5. int hashCode() : Returns a hash code value of Object.
  6. void notify() : Wakes up a single thread that is waiting on this object’s monitor. It works in multithread env with tow thread only.
  7. void notifyAll() : Wakes up all threads that are waiting on this object’s monitor. if more than one thread running.
  8. String toString() : Returns string representation of object.
  9. void wait() : Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
  10. void wait(long timeout) : Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. or specified time has elapsed.
  11. void wait(long timeout, int nanos) : Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

In this below examples you can see how to override and utilize these methods in different ways.

Example of clone() method

Object class clone() method, create and return copy of a object(). For implementing a clone method class have implements Cloneable interface which is a Marker Interface. There are two ways of cloning of object Shallow Cloning and Deep Cloning. For more detail follow below link.

Java : Shallow and Deep Object Cloning

Eample of finalize() method

Garbage collector calls Object class finalize() method before clean object. We can override this method for code clean-up activity like closing files, database connection and socket. Follow below link to know more about finalize() method example and uses:

Java : Garbage Collection finalize() method example and uses

Example of hashCode(), equals() and toString() method

Override toString() method to print object values. Same way we can override hash() code and equals() method also. hashcode and equals() method have contract as:

“If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. If you only override equals() and not hashCode() your class violates this contract

For example of toString(), hashcode() and equals() follow below link:

Java : How to remove duplicate objects from list?

Example of getClass() method

The getClass() method returns the run time class of an object.  As in below examples returning class name of objects.

import java.util.Calendar;

public class GetClassExample {

	public static void main(String[] args) {
		GetClassExample test=new GetClassExample();

		System.out.println("Class Name :"+test.getClass().getName());

		Calendar calendar=Calendar.getInstance();
		System.out.println("Calendar Class Name :"+calendar.getClass().getName());

		Integer integer=new Integer(10);
		System.out.println("Integer Class Name :"+integer.getClass().getName());

	}
}

Output


Class Name :com.Object.GetClassExample
Calendar Class Name :java.util.GregorianCalendar
Integer Class Name :java.lang.Integer

Example of wait(), notify() and notifyAll() method

Below is example of restaurant using method wait(), notify() and notifyAll(). Where Two waiter thread are running and waiting for  order message when they got order notify will pass the order message and based on available waiter will process order.

public class Order {
    private String msg;
    public Order(String msg){
        this.msg=msg;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String str) {
        this.msg=str;
    }
}

Waiter class that will wait for other threads to invoke notify methods to complete it’s processing. Notice that Waiter thread is owning monitor on Order object using synchronized block.

public class Waiter implements Runnable{
    private Order msg;
    public Waiter(Order msg){
        this.msg=msg;
    }
    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        synchronized (msg) {
            try{
                System.out.println(name+" waiting to get notification at time:"+System.currentTimeMillis());
                msg.wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            System.out.println(name+" waiter thread got notification at time:"+System.currentTimeMillis());
            //process the order now
            System.out.println(name+" processed: "+msg.getMsg());
        }
    }
}

Here notification thread will call notify() method on order message so that available waiter will pick the order.Notice that synchronized block is used to own the monitor of Order object.

public class Notification implements Runnable {
    private Order msg;
    public Notification(Order msg) {
        this.msg = msg;
    }
    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        System.out.println(name+" started");
        try {
            Thread.sleep(1000);
            synchronized (msg) {
                msg.setMsg(name+" Notification work done");
                msg.notify();
                //use notify all when lots of thread are running
                // msg.notifyAll();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Below test class having multiple threads of Waiter and notification to execute order.

public class WaitNotifyExample {
	public static void main(String[] args) {
		Order order= new Order("My Order");
	        Waiter waiter1 = new Waiter(order);
	        new Thread(waiter1,"waiter 1").start();

	        Waiter waiter2 = new Waiter(order);
	        new Thread(waiter2, "waiter 2").start();

	        Notification notification = new Notification(msg);
	        new Thread(notification, "notification").start();
	        System.out.println("All the threads are started");
	}
}

When we will execute the above program, we will see below output but program will not complete because there are two waiter threads waiting for Order object and notify() method has wake up only one of them, the other waiter thread is still waiting to get notified.

Output


waiter 2 waiting to get notification at time:1552127934935
waiter 1 waiting to get notification at time:1552127934935
notification started
All the threads are started
waiter 2 waiter thread got notification at time:1552127935946
waiter 2 processed: notification Notification work done

or


waiter 1 waiting to get notification at time:1552127972873
All the threads are started
notification started
waiter 2 waiting to get notification at time:1552127972873
waiter 1 waiter thread got notification at time:1552127973876
waiter 1 processed: notification Notification work done

Conclusion

Here you learn about the Object class and it’s methods. How to use these objects class methods with example and where can we use that.

References

https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html

Java : Immutable Class/Collection Creation


What is Mutable/Immutable Class?

A class is called as immutable class once object is created , we can not change it’s fields/objects values. If values are changeable then it’s mutable class.

Designing Rule

Classes should be immutable unless there’s a very good reason to make them mutable….
If a class cannot be made immutable, limit its mutability as much as possible.

In java all the wrapper classes and String class is immutable. For Ex: immutable classes like String, Boolean, Byte, Short, Integer, Long, Float, Double etc.

How to make a class Immutable Class?

Below are step by step guide to make a class Immutable:

Step 1 : Don’t provide “setter” methods that modify fields or objects referred to by fields.
Step 2 : Make all fields final and private.
Step 3 : Don’t allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
Step 4 : If the instance fields include references to mutable objects, don’t allow those objects to be changed: Don’t provide methods that modify the mutable objects.
Step 5 : Don’t share references to the mutable objects. Never store references to external, mutable objects passed to the constructor.
If necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.

What are Benefits of Immutable Object?

  1. Immutable objects are thread-safe so you will not have any synchronization issues.
  2. Immutable objects are good Map keys and Set elements, since these typically do not change once created.
  3. Immutability makes it easier to write, use and reason about the code (class invariant is established once and then unchanged)
  4. Immutability makes it easier to parallelize your program as there are no conflicts among objects.
  5. Immutable objects internal state of your program will be consistent even if you have exceptions.
  6. References to immutable objects can be cached as they are not going to change.

How to create Immutable Lists, Sets or Maps?

In JAVA 8 added “unmodifiable” method and JAVA 9 added “of” factory method to make collections like lists, sets and maps as immutable.  for example :

JAVA 8


Unmodifiable List
List stringList = Arrays.asList("Facing", "Issues", "On", "IT");
stringList = Collections.unmodifiableList(stringList);

Unmodifiable Set
Set stringSet = new HashSet<>(Arrays.asList("Facing", "Issues", "On", "IT"));
stringSet = Collections.unmodifiableSet(stringSet);

Unmodifiable Map
Map<String,Integer> stringMap = new HashMap<String, Integer>();
stringMap.put("Facing",1);
stringMap.put("Issues",2);
stringMap.put("On",3);
stringMap.put("IT",4);
stringMap = Collections.unmodifiableMap(stringMap);

JAVA 9


Unmodifiable List
List stringList = List.of("Facing", "Issues", "On", "IT");
Unmodifiable Set
Set stringSet = Set.of("Facing", "Issues", "On", "IT");

Unmodifiable Map
Map stringMap = Map.of("Facing",1, "Issues",2, "On",3, "IT",4);

 

Immutable Class Example


//make class final so that method not override
public final class ImmutableClass {
	final String pancardNumber;
	final String aadharNumber;
	final DOB dob;

	// Create object
	public ImmutableClass(String pancardNumber, String aadharNumber, DOB dob) {
		this.pancardNumber = pancardNumber;
		this.aadharNumber = aadharNumber;
		this.dob = dob;
	}
    //No setter method so that no fields get modifiable
	public String getPancardNumber() {
		return pancardNumber;
	}

	public String getAadharNumber() {
		return aadharNumber;
	}

	@Override
	public String toString() {
		return "ImmutableClass [pancardNumber=" + pancardNumber + ", aadharNumber=" + aadharNumber + ", dob=" + dob
				+ "]";
	}
}
public class  DOB {
	private int day;
	private int month;
	private int year;
	public DOB(int day, int month, int year)
	{
	this.day=day;
	this.month=month;
	this.year=year;
	}

	public int getDay() {
		return day;
	}

	public int getMonth() {
		return month;
	}

	public int getYear() {
		return year;
	}

	@Override
	public String toString() {
		return "DOB [day=" + day + ", month=" + month + ", year=" + year + "]";
	}

}
public class ImmuTableClassTest {

	public static void main(String[] args) {
		DOB dob = new DOB(24, 04, 1992);
		ImmutableClass immutableClass = new ImmutableClass("ABCD12345", "1234567890123456", dob);
		System.out.println(immutableClass);

	}

}

Output


ImmutableClass [pancardNumber=ABCD12345, aadharNumber=1234567890123456, dob=DOB [day=24, month=4, year=1992]]

Conclusion

In this blog you understand below points:

  • What is mutable and Immutable classes?
  • How make a class Immutable?
  • How to make collections like Lists, Sets and maps  immutable by Java 8 and Java 9?
  • Immutable class example.

References

https://docs.oracle.com/javase/9/core/creating-immutable-lists-sets-and-maps.htm