Core Java Tutorials


Introduction

Java Hello World

Java Compilation

JDK New Features

JVM Architecture

Java OOPs Concepts

Java Package

Array

Exception Handling

String

Immutable Class

File Handling

Serialization

MultiThreading

Volatile

Concurrent Package

Collection

Collection Internal

Generics

Cloning

Reflection In Java

Annotation

Class Loader

Java Inner classes

Garbage Collector

JDBC

References In Java

Heap Dump & Thread Dump

HashSet in Collection class Hierarchy:-


HashSet Example with String:-

import java.util.*;
public class HashSetExample {
	public static void main(String[] args) {
		//default capacity is 16
		//default load factor =.75
		Set sets=new HashSet<>(16);
		sets.add("AK");
		sets.add("PK");
		sets.add("DK");
		sets.add("CK");
		//add method returns boolean value
		//true if element is added otherwise false
		boolean b=sets.add("HK");
		System.out.println("xxxx = "+b);
		sets.add("AM");
		sets.add("SK");
		for(String str:sets) {
			System.out.println(str);
		}	
  }
}
 output:-
xxxx = true
HK
PK
AK
SK
AM
CK
DK

HashSet Example with Dog class:-

 Defining a class Dog


 HashSet Example with Dog


 Adding Duplicate(violating hashset contract) Dog into HashSet
 Overriding hashCode & equals method(HashSet)
 Why search operation takes constant time in HashSet?

 HashSet class offers constant time performance for the basic operations add, remove, and size assuming the hash function disperses the elements properly among the buckets