Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Looking for tips on using List or ArrayList instead of Array

 
Dan Grindstaff
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, I have implemented some code to remove dups from an array. I would very much like to advance on to using ArrayList or List but need some pointers on where to do so. In particular, I don't want to have to instantiate an array at a size that may or may not work. Thanks very much.



console output:
robertbrendapaul
robetndpul
 
Marco Ehrentreich
best scout
Bartender
Posts: 1294
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Dan,

you could save yourself a lot of time by using a Set instead of a List. A Set automatically takes care that it does not contain any duplicates! Duplicates are determined by the equals() method of an object so the class of the objects you want to store inside a Set should override equals() and hashCode() accordingly. Class Character (which is the wrapper class of "char" you are using) already does this. You should get away with something like this:

Now you should only see character 'a' once in the output ;-)

Marco

PS: The Java Collection Framework and other 3rd party libraries offer a lot more features of this kind. So in Java you typically don't have to worry about such low-level details and in general it's better (more performant, robust, secure, ...) to use existing solutions instead of your own ones!
 
Campbell Ritchie
Sheriff
Posts: 48454
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don’t think your isUnique method does what it claims to do. It is the opposite of a contains() method, as you have written it.
You can read about Lists, Sets, etc in the Java Tutorials.
 
Randall Twede
Ranch Hand
Posts: 4363
2
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i use collections classes when an array wont work.
if i know the length i use array...if not i use ArrayList(you could also use Vector)
and as was mentioned Set eliminates duplicates
Map is often what you want also
read up about them
 
Campbell Ritchie
Sheriff
Posts: 48454
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Avoid Vector; it is usually regarded as inefficient, almost legacy code. There are a few places, eg JComboBox constructors, however, where its use may be unavoidable.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic