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
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.
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.
Constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75).
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 .
Set does not allow duplicates. As strings are put into a pool, they all point to the same instance.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With