Wednesday, February 23, 2011

Chapter 45: Using Sets

Sets are extremely useful for cases where you don't want to sit and write code around your collections to ensure that there are no duplicates. Actually, why would you when Java gives you a powerful class that does all this for you. In this chapter we are going to look at Sets that give us the very feature we talked about in the previous 2 lines.

So, lets get started!!!

Using Sets

Remember that Sets are used when you don’t want any duplicates in your collection. If you attempt to add an element to a set that already exists in the set, the duplicate element will not be added, and the add() method will return false. Remember, HashSets tend to be very fast because, as we discussed earlier, they use hashcodes.

You can also create a TreeSet, which is a Set whose elements are sorted. You must use caution when using a TreeSet (we’re about to explain why):

import java.util.*;
class MyFirstSetExample {
public static void main(String[] args) {
boolean[] ba = new boolean[5];
// insert code here

ba[0] = s.add("a");
ba[1] = s.add(new Integer(42));
ba[2] = s.add("b");
ba[3] = s.add("a");
ba[4] = s.add(new Object());
for(int x=0; x < ba.length; x++) System.out.print(ba[x] + " "); System.out.println("\n"); for(Object o : s) System.out.print(o + " "); } } If you insert the following line of code you’ll get output something like this: Set s = new HashSet(); // insert this code true true true false true a java.lang.Object@e09713 42 b It’s important to know that the order of objects printed in the second for loop is not predictable: HashSets do not guarantee any ordering. Also, notice that the fourth invocation of add() failed, because it attempted to insert a duplicate entry (a String with the value a) into the Set. If you insert this line of code you’ll get something like this: Set s = new TreeSet(); // insert this code Exception in thread "main" java.lang.ClassCastException: java. lang.String at java.lang.Integer.compareTo( at at java.util.TreeMap.put( at java.util.TreeSet.add( The issue is that whenever you want a collection to be sorted, its elements must be mutually comparable. Remember that unless otherwise specified, objects of different types are not mutually comparable. You can go back to the Chapter on Sorting Collections if you want to refresh the collection sorting fundamentals.

Previous Chapter: Chapter 44 - Using Lists

Next Chapter: Chapter 46 - Using Maps

No comments:

Post a Comment

© 2013 by All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.


Google+ Followers