Creating a Set

A set is a collection that holds unique values. Adding a value that's already in the set has no effect.
// Create the set Set set = new HashSet(); // Add elements to the set set.add("a"); set.add("b"); set.add("c"); // Remove elements from the set set.remove("c"); // Get number of elements in set int size = set.size(); // 2 // Adding an element that already exists in the set has no effect set.add("a"); size = set.size(); // 2 // Determining if an element is in the set boolean b = set.contains("a"); // true b = set.contains("c"); // false // Iterating over the elements in the set Iterator it = set.iterator(); while (it.hasNext()) { // Get element Object element = it.next(); } // Create an array containing the elements in the set (in this case a String array) String[] array = (String[])set.toArray(new String[set.size()]);

Comments

17 Jan 2010 - 10:33pm by Anonymous (not verified)

thanx 4 sharing..........

9 Mar 2010 - 1:38am by Anonymous (not verified)

b = set.contains("c"); // true
b = set.contains("C"); // true

9 Mar 2010 - 1:39am by Anonymous (not verified)

last posting is not correct.

b = set.contains("c"); // true
b = set.contains("C"); // False

24 Mar 2010 - 4:53pm by Roiw (not verified)

Thanks a lot man keep doing you great work.

16 May 2010 - 8:57am by Anonymous (not verified)

is there a way to add all the letters (a,b,c) in one go ??
thanks

31 May 2010 - 1:48am by Anonymous (not verified)

thank you

14 Jun 2010 - 11:49pm by Anonymous (not verified)

hi u can add the elements to list in one go

String[] abc={"a","b","c","a"};
Set obj=new HashSet(Arrays.asList(abc));--- which converts arrays to set

String[] unique=(String[]) obj.toArray(new String[obj.size()]);
---> it will return unique values i,e unique contain ["a","b","c"]

30 Jun 2010 - 3:04am by rea mae (not verified)

tnx 4 giving this kind of answer....

29 Jul 2010 - 3:47am by Anonymous (not verified)

thank you

29 Jul 2010 - 3:49am by Anonymous (not verified)

I cant understood.Can you explain briefly?

29 Jul 2010 - 3:49am by Anonymous (not verified)

b = set.contains("C"); // true

21 Aug 2010 - 3:44pm by Tahlil (not verified)

Thanks very much for this example :)

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.