0

I have made a Hashset of StringBuilder.

The below code returns "true" even if that StringBuilder is present in Hashset:

if(!contains(sb_obj))
{
...
}

Also I have made a ArrayList of StringBuilder.

The below code returns "-1" even if ArrayList contains obj:

if(arr.indexOf(obj)==-1)
{
....
}

Why such behaviour?

danday74
  • 52,471
  • 49
  • 232
  • 283
ttripdee
  • 33
  • 1
  • 6

2 Answers2

0

I assume you are comparing different StringBuilder objects that have the same String values.

StringBuilder doesn't override equals and hashCode methods. This causes HashSet and ArrayList to use Object's implementation of them which compares by identity. Since you are comparing different objects they are different.

Oleg
  • 6,124
  • 2
  • 23
  • 40
0

Please use String instead of storing StringBuilder object or if you want to store custom object override hashcode and equals methods whenever you are trying to add and search back that object.

Please read the concept of hascode and equals method, you can find many examples over internet.

Deepak Singh
  • 411
  • 1
  • 5
  • 13