Set Interface and HashSet Implementation

When we discuss about Set, one word must come to our mind is uniqueness i.e Set will not allow duplicates.

Set will allow null value, but it will allow only one null value

Set involves  three implementations.

  1. HashSet
  2. LinkedHashSet
  3. TreeSet

1. HashSet

When we talk about hashset we must remember some of the key points which is mentioned below.

  1. HashSet will not allow duplicates.
  2. Allow only one null value.
  3. It is an unsorted set.
  4. It is an unorderd set. So we cant predict the order of displaying while iterating the hashset.
  5. It is not threadsafe.
  6. It will not allow Random Access or retrieval.

Now we will see the implementation of Hashset.

CODE


package HashSet;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class HashSet_Integer_StringImplementation {
public static void main(String[] args) {
//String Implementation
System.out.println("String Implementation");
Set<String> stringSet = new HashSet();
stringSet.add("learn");
stringSet.add("from");
stringSet.add("examples");
stringSet.add("learn");
stringSet.add("from");
stringSet.add("shidhar");
System.out.println("String set values are :"+stringSet);
//Integer Implementation
System.out.println("Integer Implementation");
Set<Integer> integerSet = new HashSet<>();
integerSet.add(34);
integerSet.add(234);
integerSet.add(4);
integerSet.add(34);
System.out.println("Integer set values are :"+integerSet);
}
}

Output

String Implementation
String set values are :[shidhar, learn, from, examples]
Integer Implementation
Integer set values are :[34, 4, 234]

If we notice the output, we will see that hashset will not allow duplicates. Also in hashset we will not be having set() or get() methods because hashset will not allow Random access or retrieval.

We have seen hashset implementation for String and Integer Wrapper class, but we didn’t see how hashset will behave for User Defined Objects because hashset behave in different way for adding User Defined objects. In order to avoid duplicates for user defined objects we must have to override the equals and hashcode or else it will not avoid duplicates.

ArrayList, Vector and LinkedList

ArrayList

ArrayList is like a array which size will be grown dynamically. Some of the main features of arraylist are given below

  1. Arraylist allows duplicates.
  2. It allows null, also it will allow multiple null.
  3. It’ s not threadsafe which means it is not synchronized.
  4. Arraylist will maintain insertion order
  5. It will not be sorted. (since it maintain insertion order it will not be sorted.) But we can sort the arrralylist using Collections.sort(). We will see arraylist sorting in a more detailed manner soon.
  6. It can be traverse using
    • For each
    • Iterators
    • Indexes

Note: Collections will not allow primitives. So when primitive is added to a collection, it get automatically converted into its equivalent Wrapper Class and loaded as an object into the collection.

ArrayList

package ArrayList;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ArrayListImplementation {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		List integerList = new ArrayList();

		//Adding an Object, int will be automatically
		//converted to Wrapper class
		integerList.add(1);
		integerList.add(2);
		integerList.add(34);
		integerList.add(4);
		integerList.add(3);
		System.out.println("Values in integerList "+integerList);

		integerList.add(3, 98);
		System.out.println("Values in integerList after adding"
				+ " in a specified (3rd) position"+integerList);

		/* addAll -> will add a collection
		   of List objects to another list */
		List integerListTwo = new ArrayList();
		integerListTwo.add(65);
		integerListTwo.add(73);
		integerList.addAll(integerListTwo);
		System.out.println("Values in integerListTwo " +integerListTwo);
		System.out.println("Values in integerList after adding"
				+ " in a Collection (another list)"+integerList);

		/*addAll -> will also a collection of List objects
		to another list at a specified position*/  

		integerList.addAll(6, integerListTwo);
		System.out.println("Values in integerListTwo after adding"
				+ " in a specified (6th) position of integerList "+integerList);

		//contains  -> Returns true if this list contains the specified element.
		System.out.println("Check integerList contains 5 or not :"+integerList.contains(5));

		//containsAll  -> Returns true if this list contains the specified collection (integerListTwo).
		System.out.println("Check integerList contains integerListTwo "
				+ "collection or not :"+integerList.containsAll(integerListTwo));

		//equals
		System.out.println(integerList.equals(integerListTwo));
		System.out.println(integerList.equals(integerList));

		//get -> Returns the element at the specified position in this list
		System.out.println("Get the element at the specified positon "+ integerList.get(8));

		//indexOf  -> Returns the index of the first occurrence of the specified
		//element in this list, or -1 if this list does not contain the element.
		System.out.println("Index of 73 is at "+integerList.indexOf(73));

		//Iterator -> Returns an iterator over the elements in this list in proper sequence.
		System.out.println("Elements in iterator");
		System.out.println("--------------------");
		Iterator iterator=integerList.iterator();
		while (iterator.hasNext()) {
			System.out.println(iterator.next());
		}

		//lastIndexOf -> Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element
		System.out.println("lastIndexOf of 3 is :"+integerList.lastIndexOf(3));

		//set -> Replaces the element at the specified position in this list with the specified element (optional operation).
		integerList.set(0, 18);
		System.out.println("After setting 18 at 0th position, value of integerLis"+integerList);

		//size -> Returns the number of elements in this list. If this list contains more than
		//Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.
		System.out.println("Size of integerList :"+integerList.size());

		//remove ->Removes the element at the specified position in this list (optional operation).
		//Shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the list.
		integerList.remove(2);
		System.out.println(" remove 34 which is at 2nd position: "+integerList);

		//removeAll ->Removes from this list all of its elements that are contained in the specified collection (optional operation).
		integerList.removeAll(integerListTwo);
		System.out.println("After removing integerListTwo :"+integerList);		

		integerList.addAll(integerListTwo);
		//retainAll -> Retains only the elements in this list that are contained
		//in the specified collection (optional operation).In other words, removes from this list all
		//of its elements that are not contained in the specified collection.
		integerList.retainAll(integerListTwo);

		System.out.println("retain all will remove all elements except integgerListTwo :"+integerList);		

		/*clear ---> Removes all of the elements from this list (optional operation).
		The list will be empty after this call returns.*/
		integerList.clear();

		System.out.println("After clearing the list :"+integerList);

		//isEmpty() --> will check whether the list is empty or not
		System.out.println("checking the list is empty or not :"+integerList.isEmpty());

	}
}

 



Output is:

Values in integerList [1, 2, 34, 4, 3]
 Values in integerList after adding in a specified (3rd) position[1, 2, 34, 98, 4, 3]
 Values in integerListTwo [65, 73]
 Values in integerList after adding in a Collection (another list)[1, 2, 34, 98, 4, 3, 65, 73]
 Values in integerListTwo after adding in a specified (6th) position of integerList [1, 2, 34, 98, 4, 3, 65, 73, 65, 73]
 Check integerList contains 5 or not :false
 Check integerList contains integerListTwo collection or not :true
 false
 true
 Get the element at the specified positon 65
 Index of 73 is at 7
 Elements in iterator
 --------------------
 1
 2
 34
 98
 4
 3
 65
 73
 65
 73
 lastIndexOf of 3 is :5
 After setting 18 at 0th position, value of integerLis[18, 2, 34, 98, 4, 3, 65, 73, 65, 73]
 Size of integerList :10
 remove 34 which is at 2nd position: [18, 2, 98, 4, 3, 65, 73, 65, 73]
 After removing integerListTwo :[18, 2, 98, 4, 3]
 retain all will remove all elements except integgerListTwo :[65, 73]
 After clearing the list :[]
 checking the list is empty or not :true

package ArrayList;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class linkedListImplementation {

	public linkedListImplementation() {
		// TODO Auto-generated constructor stub
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		List integerList = new LinkedList();

		//Adding an Object, int will be automatically
		//converted to Wrapper class
		integerList.add(1);
		integerList.add(2);
		integerList.add(34);
		integerList.add(4);
		integerList.add(3);
		System.out.println("Values in integerList "+integerList);

		integerList.add(3, 98);
		System.out.println("Values in integerList after adding"
				+ " in a specified (3rd) position"+integerList);

		/* addAll -> will add a collection
		   of List objects to another list */
		List integerListTwo = new LinkedList();
		integerListTwo.add(65);
		integerListTwo.add(73);
		integerList.addAll(integerListTwo);
		System.out.println("Values in integerListTwo " +integerListTwo);
		System.out.println("Values in integerList after adding"
				+ " in a Collection (another list)"+integerList);

		/*addAll -> will also a collection of List objects
		to another list at a specified position*/  

		integerList.addAll(6, integerListTwo);
		System.out.println("Values in integerListTwo after adding"
				+ " in a specified (6th) position of integerList "+integerList);

		//contains  -> Returns true if this list contains the specified element.
		System.out.println("Check integerList contains 5 or not :"+integerList.contains(5));

		//containsAll  -> Returns true if this list contains the specified collection (integerListTwo).
		System.out.println("Check integerList contains integerListTwo "
				+ "collection or not :"+integerList.containsAll(integerListTwo));

		//equals
		System.out.println(integerList.equals(integerListTwo));
		System.out.println(integerList.equals(integerList));

		//get -> Returns the element at the specified position in this list
		System.out.println("Get the element at the specified positon "+ integerList.get(8));

		//indexOf  -> Returns the index of the first occurrence of the specified
		//element in this list, or -1 if this list does not contain the element.
		System.out.println("Index of 73 is at "+integerList.indexOf(73));

		//Iterator -> Returns an iterator over the elements in this list in proper sequence.
		System.out.println("Elements in iterator");
		System.out.println("--------------------");
		Iterator iterator=integerList.iterator();
		while (iterator.hasNext()) {
			System.out.println(iterator.next());
		}

		//lastIndexOf -> Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element
		System.out.println("lastIndexOf of 3 is :"+integerList.lastIndexOf(3));

		//set -> Replaces the element at the specified position in this list with the specified element (optional operation).
		integerList.set(0, 18);
		System.out.println("After setting 18 at 0th position, value of integerLis"+integerList);

		//size -> Returns the number of elements in this list. If this list contains more than
		//Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.
		System.out.println("Size of integerList :"+integerList.size());

		//remove ->Removes the element at the specified position in this list (optional operation).
		//Shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the list.
		integerList.remove(2);
		System.out.println(" remove 34 which is at 2nd position: "+integerList);

		//removeAll ->Removes from this list all of its elements that are contained in the specified collection (optional operation).
		integerList.removeAll(integerListTwo);
		System.out.println("After removing integerListTwo :"+integerList);		

		integerList.addAll(integerListTwo);
		//retainAll -> Retains only the elements in this list that are contained
		//in the specified collection (optional operation).In other words, removes from this list all
		//of its elements that are not contained in the specified collection.
		integerList.retainAll(integerListTwo);

		System.out.println("retain all will remove all elements except integgerListTwo :"+integerList);		

		/*clear ---> Removes all of the elements from this list (optional operation).
		The list will be empty after this call returns.*/
		integerList.clear();

		System.out.println("After clearing the list :"+integerList);

		//isEmpty() --> will check whether the list is empty or not
		System.out.println("checking the list is empty or not :"+integerList.isEmpty());

	}
}

Output:

Values in integerList [1, 2, 34, 4, 3]
Values in integerList after adding in a specified (3rd) position[1, 2, 34, 98, 4, 3]
Values in integerListTwo [65, 73]
Values in integerList after adding in a Collection (another list)[1, 2, 34, 98, 4, 3, 65, 73]
Values in integerListTwo after adding in a specified (6th) position of integerList [1, 2, 34, 98, 4, 3, 65, 73, 65, 73]
Check integerList contains 5 or not :false
Check integerList contains integerListTwo collection or not :true
false
true
Get the element at the specified positon 65
Index of 73 is at 7
Elements in iterator
——————–
1
2
34
98
4
3
65
73
65
73
lastIndexOf of 3 is :5
After setting 18 at 0th position, value of integerLis[18, 2, 34, 98, 4, 3, 65, 73, 65, 73]
Size of integerList :10
remove 34 which is at 2nd position: [18, 2, 98, 4, 3, 65, 73, 65, 73]
After removing integerListTwo :[18, 2, 98, 4, 3]
retain all will remove all elements except integgerListTwo :[65, 73]
After clearing the list :[]
checking the list is empty or not :true

Difference between ArrayList and Linked list

Reason ArrayList Linked List
Search Faster because it has index based search. Eg get(index) Slower.Since it implements doubly linked list which requires traversal through all the elements to search an element.
Deletion Slower Faster
Insertion Faster Slower

 

Similarities:

• Both implements List interface and extends AbstractList.
• Both will maintain Insertion Order.
• Both are non-synchronized (non threadsafe).
• Both can be made synchronized by using Collections.synchronizedList method

When to use Linked List and When to use arraylist:
1. For insertion and deletion go for linked list.
2. For search go for arraylist.