Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashset size issue

Tags:

java

hashset

Here In below example i have created hashset in which i am adding three string values s1,s2,s3 though it shows me size of hashset 1. Why?

public static void main(String args[])
{
    String s1="abc";
    String s2=new String("abc");
    String s3="abc";
    Set setdemo=new HashSet();
    setdemo.add(s1);
    setdemo.add(s2);
    setdemo.add(s3);

    System.out.println("s1 hashcode -:"+ System.identityHashCode(s1));
    System.out.println("s2 hashcode -:"+ System.identityHashCode(s2));
    System.out.println("s3 hashcode -:"+ System.identityHashCode(s3));
    System.out.println("Set size is -:"+setdemo.size());
}

output:

s1 hashcode -:17523401
s2 hashcode -:8567361
s3 hashcode -:17523401
Set size is -:1
like image 206
Mahesh Pachpande Avatar asked Mar 18 '13 09:03

Mahesh Pachpande


People also ask

How do I set the size of a HashSet?

HashSet. size() method is used to get the size of the HashSet or the number of elements present in the HashSet. Parameters: This method does not takes any parameter. Return Value: The method returns the size or the number of elements present in the HashSet.

How HashSet increases its size?

The HashSet capacity is doubled when the load factor (0.75) is reached. As the documentation explains: The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased.

What is the default size of HashSet?

Constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75).

Is HashSet faster than set?

A TreeSet is a set where the elements are sorted (and thus ordered), a HashSet is a set where the elements are not sorted or ordered. A HashSet is typically a lot faster than a TreeSet .


2 Answers

Set does not allow duplicates. As strings are put into a pool, they all point to the same instance.

like image 182
Sudhanshu Umalkar Avatar answered Oct 16 '22 17:10

Sudhanshu Umalkar


Duplicate is identified as having an equivalent hash code, and returning true when tested for equality.

In your case, all the 3 Strings are identified as duplicates and since Set eliminates duplicates, the size is 1 in your case.

like image 2
Rahul Avatar answered Oct 16 '22 19:10

Rahul