java left logo
java middle logo
java right logo
 

Home arrow Java SE Tips arrow java.util arrow How to create a Set
 
 
Main Menu
Home
Java Tutorials
Book Reviews
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Java Network
Java Forums
Java Blog




Most Visited Tips
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Book Reviews
Top Rated Tips
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Book Reviews


Statistics
Registered Users: 4084
Java SE Tips: 614
Java ME Tips: 202
Java EE Tips: 183
Other API Tips: 779
Java Applications: 298
Java Libraries: 209
Java Games: 16
Book Reviews:
 
 
 
How to create a Set E-mail
User Rating: / 61
PoorBest 

This Java tip illustrates a method of creating a Set. A set is a group of unique elements. If an element is already present in a set it cannot be added in the set.

    // Create a set
    Set set = new HashSet();
    
    // Add some elements to the set
    set.add("a");
    set.add("b");
    set.add("c");
    
    // Remove elements from the set
    set.remove("c");
    
    // Retrieve number of elements in the set
    int size = set.size();          // 2
    
    // Adding an element that already exists has no effect
    set.add("a");
    size = set.size();              // 2
    
    // Identifying the presence of an element 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 (ex. string) of all elements in the set
    String[] array = (String[])set.toArray(new String[set.size()]);


 Related Tips

 
< Prev   Next >
 
       
         
     
 
 
 
   
 
 
java bottom left
java bottom middle
java bottom right
RSS 0.91 FeedRSS 1.0 FeedRSS 2.0 FeedATOM FeedOPML Feed

Home - About Us - Privacy Policy
Copyright 2005 - 2008 www.java-tips.org
Java is a trademark of Sun Microsystems, Inc.