Thursday, June 25, 2009

How to Create a Set


Difference between List and Set : List can contain duplicate elements. Set can contain only unique elements. If you try to add the same element again then it will overwrite the new element on old one.

// Create the set
Set set = new HashSet();
// Add elements to the set
set.add("X");
set.add("Y");
set.add("Z");

// Adding an element that already exists in the set has no effect
set.add("X");
size = set.size(); // 3

// Remove elements from the set
set.remove("Z"); //set=["X","Y"]


// Determining if an element is in the set
boolean b = set.contains("A"); // true
b = set.contains("Z"); // false

0 comments:

 

Sample Java Codes Copyright © 2008 Green Scrapbook Diary Designed by SimplyWP | Made free by Scrapbooking Software | Bloggerized by Ipiet Notez