• Post Reply Bookmark Topic Watch Topic
  • New Topic

Basic ArrayList.contains( ) doubt  RSS feed

 
krithika desai
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
Am using the following code to figure out if an array contains duplicates.
ie the itemCode which is a String ( see Code) repeats, am supposed to abort the process.
am using ArrayList.contains() to acheive this. Hope ArrayList.contains() calls equals() on the objects and String's equals() has been overriden to compare the string content.
It is failing to detect the duplicates in certain circumstances.
Do you see a bug in this code / is my assumption about the way contains() works is wrong?
 
VIJAY Yadlapati
Ranch Hand
Posts: 175
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have tested this with Basic DataTypes and it's working fine. Please tell those Certain circumstances where you are getting error.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Regardless of whether this works correctly or not (I don't see any problems with it either) ArrayList.contains() is a very poor way to accomplish what you want, since it has to scan through the whole ArrayList to find matching entries; this will have runtime proportional to the square of the number of list entries. A much more efficient way would be to use a Set; a HashSet would be the fastest.
Also note that the line

is redundant; either itemCode is null, or not. If it's not, then there's no use in checking it twice -- i.e.,

is just fine.
 
krithika desai
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ernest Friedman-Hill:
Set; a HashSet would be the fastest.

is just fine.

thanks for both the suggestions, especially the first one.
Yes, i just went through the javadocs and found that HashSet offers a constant time performance for contains(). As for the second, got so much used to using the AND operator that i added the redundant check for the || operator as well!.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!