Hashset size issue

Here In the example below, I created a hashset in which I add three string values ​​s1, s2, s3, although it shows me the 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
+5
source share
8 answers

Set does not allow duplication. Because the rows are placed in the pool, they all point to the same instance.

+4
source

Duplicateidentified as having an equivalent hash code and returning truewhen checking for equality .

In your case, all 3 are Stringsidentified as duplicates , and since Setexcluding duplicates, the size is 1in your case.

+2

HashSet . "abc" 3 , String abc,

0

HashSet - "". MultiSet ( Bag), , Apache Commons Guava - .

0

HashSet.add

e , e2 , (e==null ? e2==null : e.equals(e2))

, :

s2.equals(s1) true, s2 .

s3.equals(s1) true, s3 setdemo.

0

-, hash(). Set , , , .

0

s1.equals(s2)
s2.equals(s3)

String , , HashSet equals , .

0

, String, , .

String s1 = "hello";
String s2 = "hello";

s1 s2, . .equals(), , . :

setdemo.add(s1);
setdemo.add(s1);
setdemo.add(s1);

( ), , HashSet ( ) .equals, , , , HashSet 1.

0
source

All Articles