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
Set does not allow duplication. Because the rows are placed in the pool, they all point to the same instance.
Duplicateidentified as having an equivalent hash code and returning truewhen checking for equality .
Duplicate
true
In your case, all 3 are Stringsidentified as duplicates , and since Setexcluding duplicates, the size is 1in your case.
Strings
Set
1
HashSet . "abc" 3 , String abc,
HashSet - "". MultiSet ( Bag), , Apache Commons Guava - .
HashSet.add
e , e2 , (e==null ? e2==null : e.equals(e2))
e
e2
(e==null ? e2==null : e.equals(e2))
, :
s2.equals(s1) true, s2 .
s2.equals(s1)
s2
s3.equals(s1) true, s3 setdemo.
s3.equals(s1)
s3
setdemo
-, hash(). Set , , , .
s1.equals(s2) s2.equals(s3)
String , , HashSet equals , .
String
, String, , .
String s1 = "hello"; String s2 = "hello";
s1 s2, . .equals(), , . :
setdemo.add(s1); setdemo.add(s1); setdemo.add(s1);
( ), , HashSet ( ) .equals, , , , HashSet 1.