Home | FAQ | Contact me

Java Collections II

This is a collection of notes on stuff that's sort of Collections-related going beyond the first treatment.

Lists and Sets

Using a hashed set is much faster when your main activity is only to discover if a string is in a set than putting it into an array. The array has to be looked through, string by string, until a match is found. A Set's contains() method is much. Of course, you cannot install identical strings into a hashed set as you can in an array list.

List< String > list = new ArrayList< String >(); list.add( "ant" ); list.add( "cat" ); list.add( "dog" ); list.add( "aardvark" ); list.add( "dog" ); // this is okay! if( list.contains( "dog" ) ) ...

...versus...

Set< String > set = new HashedSet< String >(); set.add( "ant" ); set.add( "cat" ); set.add( "dog" ); set.add( "aardvark" ); //set.add( "dog" ); // can't do this! if( set.contains( "dog" ) ) // this is much faster than with List ...