Let's learn java programming language with easy steps. This Java tutorial provides you complete knowledge about java technology.

Showing posts with label COLLECTION. Show all posts
Showing posts with label COLLECTION. Show all posts

Thursday, 31 August 2017

Difference Between HashSet and HashMap in Java

HashSet vs HashMap

HashSet vs HashMap

Here we will discuss, what is the difference between HashSet and HashMap in java. This is really very nice and useful and mostly asked java interview question.

In the last post, we have discussed that what is the difference between HashMap and Hashtable class in java collection framework but here we will learn only what is the difference between HashMap and HashSet in java with example.


Java HashSet

  • HashSet class implements the Set interface.
  • HashSet internally uses HashMap to store it elements.
  • HashSet class doesn't contain duplicate elements i.e it stores only unique elements.
  • In HashSet, There is no key-value combination for storing data. We can insert only elements or values.
  • According to some developers, Java HashSet performance is slower than HashMap.
  • HashSet uses add(object) method to store the elements.
  • There are only one null value allow in hash set.


HashSet Example in Java

This is the simple java HashSet example where we will insert some elements and iterate all the elements one by one.

import java.util.*;
class Demo
{
public static void main(String args[])
{
//declaring hash set
Set<String> hs = new HashSet<String>();
hs.add("java");//inserting elements
hs.add("c++");
hs.add("c#");
hs.add("html");
hs.add("css");
hs.add("java");
hs.add(null);

//iterating one by one
Iterator i = hs.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}

Output: c#
             null
             c++
             html
             java
             css


Java HashMap

  • HashMap class implements Map interface.
  • HashMap class internally uses array of Entry<k,v> to store the elements.
  • HashMap class doesn't allow duplicate key but it allows duplicate values.
  • HashMap uses key-value combination for storing the data.
  • HashMap performance is faster than HashSet in java.
  • HashMap uses put(key, value) method to store the data.
  • There can be one null key and multiple null values in hash map.


HashMap Example in Java


This is the second example in HashSet vs HashMap java. Java HashMap store the data on the basis of key and value pairs.


import java.util.*;
class Simple
{
public static void main(String args[])
{
//creating HashMap

HashMap<Integer, String> hm = new HashMap<Integer, String>();
hm.put(101, "Ram");
hm.put(102, "Ram");
hm.put(103, "Suman");
hm.put(103, "Kiran");
hm.put(104, "Sekhar");
hm.put(105, "Vimal");

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

Output:  101 Ram
              102 Ram
              103 Kiran
              104 Sekhar
              105 Vimal

In the above example, There can be duplicate values in hash map but there cannot be duplicate key in hash map class in java. It overrides duplicate keys.


Similarities Between HashSet and HashMap class in Java

There are some similarities between these two classes in collection framework. These are...

HashSet Class: - HashSet class are not synchronized i.e it is not thread-safe. There is no guarantee to maintain the insertion order of an element. It provides fast performance like HashMap but HashMap is much faster than hash set.

HashMap Class: HashMap class are not synchronized like hash set class.
HashMap also does not maintain insertion order of an element like hash set class. Both hash set and hash map provide fast performance.

Read More:

Difference Between ArrayList and LinkedList in Java.
Difference Between ArrayList and Vector in Java.
Difference Between HashMap and Hashtable.
Difference Between Abstract Class and Interface in Java.
Difference Between Array and Collection.
Java Collection Interview Questions.

I hope, the difference between HashSet and HashMap in java post will help you to handle java related interviews specially in HashSet vs HashMap.


Share:

Wednesday, 23 August 2017

Difference Between HashMap and Hashtable

What is Difference Between HashMap and Hashtable in Java?

HashMap vs Hashtable

Here we will discuss, What is difference between HashMap and Hashtable in java. This is the most frequently asked question in any java interviews.


So let's start, What is the difference between hashmap and hashtable class?

Java HashMap

  • HashMap is non-synchronized i.e multiple threads can access it simultaneously. It is not a thread-safe.
  • HashMap allows one null key and multiple null values.
  • HashMap extends AbstractMap class.
  • HashMap provides fast performance.
  • HashMap is a new class and introduced in jdk 1.2.
  • HashMap returns the only iterator to traverse.
  • The iterator of HashMap is fail-fast and it throws ConcurrentModificationException.
  • It is good for single threaded applications but if you want to use HashMap class in multithreaded applications, You will have to use Collections.synchronizedMap(hashMap).


Now let's understand HashMap vs Hashtable with examples.

Java HashMap Example

This is the simple example of hash map class where we will insert some key and values and then traverse all the elements from the map.

import java.util.*;
class Demo
{
public static void main(String args[])
{
//declaring HashMap
HashMap<Integer, String> hm = new HashMap<Integer, String>();
hm.put(1000, "suman");//inserting key and value
hm.put(3000, "hari");
hm.put(99, "pooja");
hm.put(5000, "kiran");
hm.put(20000, "bheem");
for(Map.Entry m : hm.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
}
}

Output: 20000 bheem
              99 pooja
              1000 suman
              3000 hari
              5000 kiran


Note: HashMap class contains only unique elements i.e not duplicate elements and doesn't maintain insertion order of an element.


Java Hashtable

  • Hashtable is a synchronized i.e multiple threads can access it one by one. It is thread-safe.
  • Hashtable doesn't allow any null key and null values.
  • Hashtable extends Dictionary class.
  • Hashtable provides slow performance.
  • Hashtable is a legacy class.
  • Hashtable returns both Iterator as well as Enumeration for traversal.
  • Enumeration for Hashtable is not fail-fast.
  • It is good for the multithreaded environment.



Hashtable Example in Java

This is java hashtable example Where we will insert some elements and then traverse all the elements from the table.

import java.util.*;
class Test
{
public static void main(String args[])
{
//declaring Hashtable
Hashtable<Integer, String> ht = new Hashtable<Integer, String>();
ht.put(20, "red");//inserting elements
ht.put(10, "black");
ht.put(50, "yellow");
ht.put(7, "pink");
ht.put(90, "brown");
for(Map.Entry m : ht.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
}
}

Output: 10 black
             20 red
             7 pink
             50 yellow
             90 brown

Note: Hashtable class contains only unique elements i.e not duplicate elements and it doesn't maintain any insertion order of an element.


So there are many differences between HashMap and Hashtable in java and you can see other differences topics in collection framework like Difference between ArrayList and LinkedList, ArrayList and Vector, etc.

Similarities Between HashMap and Hashtable class

  1. Both implements Map interface.
  2. Both don't maintain insertion order of an element.
  3. Both store the data in the form of key and value pairs.
  4. Both using the hashing technique to store the key & value pairs.
  5. Both contain only unique elements i.e cannot allow duplicate elements
Share:

Monday, 7 August 2017

Difference Between ArrayList and LinkedList

ArrayList vs LinkedList

ArrayList vs LinkedList

Here we will learn in detail what is the difference between ArrayList and LinkedList in java programming language. This is the very important topic for the java interview.

So let's start with it.

There are many differences between array list and linked list class in java collection framework.

Java ArrayList

  • ArrayList class internally uses the dynamic array to store the elements.
  • ArrayList class provides slow manipulation because it uses internally array. If any element deletes or removes from the list or array, all the bits are shifted in memory.
  • ArrayList can work as the list only because it implements List interface only.
  • ArrayList is better for storing and accessing data or elements.

Now understand array list with an example.

Java ArrayList Example

This is the simple example of array list where we will insert elements and traverse these elements.

import java.util.*;
public class Sample
{
public static void main(String args[])
{
//Declaring ArrayList
List<String> l = new ArrayList<String>();
l.add("Apple");//inserting elements
l.add("Orange");
l.add("Mango");
l.add("Banana");
l.add("Guava");

//Traverse the elements by using Iterator interface
Iterator i = l.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}

Output: Apple
            Orange
            Mango
            Banana
            Guava

Now moving to the next class which is LinkedList class.


Java LinkedList

  • LinkedList class internally uses the doubly linked list in java to store the elements.
  • LinkedList class provides faster manipulation because it uses doubly linked list internally so no bit shifting required in memory.
  • LinkedList can work as list and queue because it implements list interface and deque interfaces.
  • LinkedList is better for manipulation data i.e inserting, deleting an elements.

Now understand linked list with an example.



Java LinkedList Example

This is the simple example of LinkedList where we will insert an element and then traverse these elements one-by-one.

import java.util.*;
public class Demo
{
public static void main(String args[])
{
//Declaring the LinkedList
LinkedList<String> ll = new LinkedList<String>();
ll.add("Red");
ll.add("Red");
ll.add("Black")';
ll.add("Blue");
ll.add("Pink");
ll.add("Green");

//Traversing elements by using Iterator interface
Iterator i = ll.iterator();
while(i.hasNext())
{
System.out.println(i.next())
}
}
}

Output: Red
             Red
             Black
             Blue
             Pink
             Green


Similarities Between ArrayList Class and LinkedList Class

In the above paragraphs, we learned some differences between these two classes but there are some similarities between array list and linked list.

  1. Both classes implement List interface.
  2. Both classes maintain insertion order of an element.
  3. Both are non-synchronized.
  4. The iterator and list iterator returned by array list and linked list class are fail-fast.
So there are many java differences which are mostly asked in java interview e.g What is the difference between ArrayList and Vector in java and difference between HashSet and LinkedHashSet, etc.


ArrayList vs LinkedList Performance

ArrayList : By the help of array list we can perform fast searching. It is good for fast searching operation. But linked list is not good for fast searching operation in the list. But array list is not good for more insert or remove operations.

LinkedList : Linked list is not good for fast searching but it is good for more insert or deletes operations.

Share:

Wednesday, 19 July 2017

Difference Between ArrayList and Vector

ArrayList vs Vector - Java Collection Framework

Difference Between ArrayList and Vector

Now here we will learn what is the differences between ArrayList and Vector class in java. " what is the differences between ArrayList and Vector in java " this is mostly asked question in any java interviews.

There are many differences between ArrayList and Vector in java collection framework. Let's see

First starts with ArrayList class.

ArrayList Class

  • ArrayList class are non-synchronized i.e multiple thread can access simultaneously. In other words, ArrayList class are not Thread safe.
  • ArrayList class is not a legacy class i.e old class in java collection.
  • ArrayList class is faster than vector class because it is non-synchronized.
  • The size increment of ArrayList class is 50% i.e half as needed.
  • ArrayList class uses Iterator interface to traverse the elements.

Java ArrayList Example

This is the simple example of java ArrayList class where we will insert some elements in this list and after inserting elements we will traverse all the elements from the array list.

import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListExample
{
public static void main(String args[])
{
//declaration of ArrayList class
ArrayList<String> al = new ArrayList<String>();
al.add("java");//insert elements
al.add("python");
al.add("c++");
al.add("c++");
al.add("html");
al.add("css");
al.add("java");

//traversing an elements by using Iterator interface
Iterator i = al.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}

output : java
              python
              c++
              c++
              html
              css
              java

In the above example, as we know ArrayList class can allow duplicate elements and maintains insertion order of an elements.

Now, move to Vector class in java collection.

Vector Class

  • Vector class is a synchronized class i.e multiple thread cannot access simultaneously, but one-by-one they can. In other words, Vector class is a Thread safe class.
  • Vector class is slower than ArrayList class because Vector class is synchronized(thread safe) class.
  • The size increment of Vector class is 100% i.e double as needed.
  • We can use both Iterator interface and Enumeration interface to traverse the elements of vector class.



Java Vector Example

In this example, we will use some method of Vector class for inserting an elements in Vector and use Enumeration interface to traverse the elements.

import java.util.*;
public class VectorExample
{
public static void main(String args[])
{
//declare Vector class
Vector<String> v = new Vector<String>();
v.add("rahul");//collection's method
v.add("ravi");
v.add("mohit");
v.addElement("rahul");//vector's method
v.addElement("love");
v.addElement("kush");

//traversing an elements by using Enumeration interface
Enumeration e = v.elements();
while(e.hasMoreElements())
{
System.out.println(e.nextElement());
}
}
}

output : rahul
              ravi
              mohit
              rahul
              love
              kush

In the above example, Vector class allows duplicate elements and maintains insertion order of an elements.

Similarities Between ArrayList and Vector Class

There are some similarities between ArrayList and Vector class in java.

(1) ArrayList and Vector both class implements List interface.
(2) ArrayList and Vector both allows duplicate elements.
(3) ArrayList and Vector both maintain insertion order of an element.
(4) By using Iterator interface we can traverse all the elements of ArrayList and Vector.
(5) Both class ArrayList and Vector class belong to the java.util package.

Visit : Java Collection Interview Questions.
Share:

Saturday, 1 July 2017

Java Queue


Java Queue Interface - Collection Framework

Java queue is an interface in java collection framework and queue interface extends collection interface. The queue interface is available in java.util.* package.

Java queue interface defines queue data structure which is normally First-In-First-Out(FIFO). In other words, Java Queue interface maintains the order of an elements in FIFO(First-In-First-Out) manner.

Java Queue interface is a data structure in which elements are added from one end and elements are deleted from another end.

In java queue, first element removed first and last element removed last.

The queue interface can be dynamically changed  during the processing i.e processed elements are removed from the queue and new elements are added to the queue.

Java collection framework contains Queue interface and also there are some other sub-interfaces which are Deque, BlockingDeque, BlockingQueue and TransferQueue.


Hierarchy of Java Queue Interface

This is the hierarchy of Queue interface in java.
Java Queue

In the given above diagram, Queue interface extends Collection interface . The PriorityQueue class extends Queue interface and Deque interface extends Queue interface.


Methods of Java Queue Interface

There are some methods of queue interface in java and these are given below :

1) boolean add(Object o)

This method inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.

2) boolean offer(Object o)

This method inserts the specified elements into this queue if it is possible to do so immediately without violating capacity restrictions.

3) Object peek()

This method retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.

4) Object remove()

This method retrieves and removes the head of this queue.

5) Object poll()

This method retrieves and removes the head of this queue, or returns null if this queue is empty.

6) Object element()

This method retrieves but doesn't removes the head of this queue.


Java PriorityQueue Class

Java PriorityQueue is a class which extends AbstractQueue class and implements Queue and Serializable interface in java.

PriorityQueue class is available in java.util.* package.

PriorityQueue class doesn't maintains the order of an elements in FIFO(First-In-First-Out) manner. This class provides the facility of using the queue in java.


Java PriorityQueue Class Example

This is an example of priority queue class where we will use some methods of Queue interface because priority queue class inherit queue interface and we will traverse the elements and removes some elements from the queue.

import java.util.*;
public class PriorityQueueExample
{
public static void main(String args[])
{
//declaring the PriorityQueue class
PriorityQueue<String> queue = new PriorityQueue<String>();
queue.add("salman");
queue.add("ranveer");
queue.add("boman");
queue.add("virat");
queue.add("dhoni");
queue.add("rohit");
System.out.println("head "+queue.element());
System.out.println("head "+queue.peek());
System.out.println("Traverse the queue elements");
Iterator itr = queue.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("after removing two elements :");
Iterator<String> itr2 = queue.iterator();
while(itr2.hasNext())
{
System.out.println(itr2.next());
}
}
}

output : head boman
              head boman
              Traverse the queue elements
              boman
              dhoni
              ranveer
              virat
              salman
              rohit
              after removing two elements :
              ranveer 
              rohit
              salman 
              virat

Share:

Monday, 26 June 2017

Collections Class In Java

Java Collections Class

Collections class in java

Collections is a class in java which is available in java.util package. Collections class inherit(extends) only Object class in java.

In java Collections class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, "wrappers", which return a new collection backed by specified collection and a few others odds and ends.

The methods of collections's class all throw a NullPointerException if the collections or class objects provided to them are null.

Collections class is a member of Java Collection Framework.


Declaration of Collections Class

public class Collections extends java.lang.Object


Fields

Following are fields for java.util.Collections class :

static List EMPTY_LIST : The empty list(immutable)

static Map EMPTY_MAP : The empty map(immutable)

static Set EMPTY_SET : The empty set(immutable)


Methods of Collections Class in Java

Take a look of some methods of Collections class.

1) static <T> boolean addAll(Collections<? super T> c, T... elements)

This method adds all of the specified elements to the specified collection.

2) static <T> Queue<T> asLifoQueue(Deque<T> deque)

This method returns a view of a Deque as a Last-in-first-out(Lifo) queue.

3) static <T> int binarySearch(List<? extends Comparable<?  super T>> list, T key)

This method searches the specified list for the specified object using the binary search algorithm.

4) static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c)

This method searches the specified list for the specified object using the binary search algorithm.

5) static <E> Collection<E> checkedCollection(Collection<E> c, Class<E> type)

This method returns a dynamically typesafe view of the specified collection.

6) static <E> List<E> checkedList(List<E> list, Class<E> type)

This method returns a dynamically typesafe view of the specified list.



7) static <K, V> Map<K, V> checkedMap(Map<K, V> m, Class<K> keyType, Class<V> valueType)

This method returns a dynamically typesafe view of the specified map.

8) static <K, V> NavigableMap<K, V> checkedNavigableMap(NavigableMap<K, V> m, Class<K> keyType, Class<V> valueType)

This method returns a dynamically typesafe view of the specified navigable map.

9) static <E> Set<E> checkedSet(Set<E> s, Class<E> type)

This method returns a dynamically typesafe view of the specified set.

10) static <T> void copy(List<? super T> dest, List<? extends T> src)

This method copies all of the elements from one list into another.

11) static <T> Enumeration<T> emptyEnumeration()

This method returns an enumeration that has no elements.

12) static <T> Iterator<T> emptyIterator()

This method returns an iterator that has no elements.


Java Collections Class Example

This is simple example of collections class.

import java.util.*;
public class CollectionsExample
{
public static void main(String args[])
{
List<String> list = new ArrayList<String>();
list.add("hindi");
list.add("english");
list.add("math");
System.out.println("before adding collection values "+list);

//using collections's method
Collections.addAll(list, "science", "drawing");
System.out.println("after adding elements collection values"+list);
}


output : before adding collection values [hindi, english, math]
        after adding elements collection values [hindi, english, math, science, drawing]


Java Collections Class Example 1

In this example, we will use max() and min() methods of collections class.

import java.util.*;
public class CollectionsExample2
{
public static void main(String args[])
{
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(96);
al.add(150);
al.add(1);
al.add(2);
al.add(33);
al.add(50);
System.out.println("maximum value"+Collections.max(al));
System.out.println("minimum value"+Collections.min(al));
}
}

output : maximum value 150
              minimum value 1

Share:

Facebook Page Likes

Follow javatutorial95 on twitter

Popular Posts

Translate