APCS Java Subset

ap.java.util
Interface Set

All Known Implementing Classes:
HashSet, TreeSet

public interface Set

A Set is a collection that contains no duplicates, that is no pair of elements e1 and e2 such that e1.equals(e2). The Set interface is only used in the AB course.

As an example, the code below determines how many different elements there are in a List. The call countDifferent(list) would return 3 for the list that follows which contains three distinct/different strings.

    ("apple", "cherry", "apple", "cherry", "cherry", "banana")
 
The code for countDifferent follows.
 public static int countDifferent(List list)
 {
     Set s = new TreeSet();
     Iterator it = list.iterator();
     while (it.hasNext()) {
         s.add(it.next());
     }
     return s.size();
 }
 


Method Summary
 boolean add(java.lang.Object o)
          Adds the parameter as an element to this set if it is not already stored in this set.
 boolean contains(java.lang.Object o)
          Returns true if this set contains the element passed as an argument, otherwise returns false.
 Iterator iterator()
          Returns an Iterator that provides access to the the elements of this set.
 boolean remove(java.lang.Object o)
          Removes the argument from this set and returns true if the argument is in this set; if not present returns false.
 int size()
          Returns the number of elements in this set.
 

Method Detail

add

public boolean add(java.lang.Object o)
Adds the parameter as an element to this set if it is not already stored in this set. If the element is added, the function returns true. If the element is not added because it is already stored in the set, the function returns false.

Parameters:
o - is the element to be added to this set
Returns:
true if o is added, false if not added because it is already in the set

contains

public boolean contains(java.lang.Object o)
Returns true if this set contains the element passed as an argument, otherwise returns false. More specifically, returns true if this set contains an element e such that e.equals(o).

Returns:
true if this set contains the argument, and false if the argument is not in this set.

remove

public boolean remove(java.lang.Object o)
Removes the argument from this set and returns true if the argument is in this set; if not present returns false.

Parameters:
o - is the element to be removed from this set
Returns:
true if element is removed, otherwise return false

size

public int size()
Returns the number of elements in this set.

Returns:
the number of elements in the set

iterator

public Iterator iterator()
Returns an Iterator that provides access to the the elements of this set. In general there is no contract for an Iterator to return elements in any particular order, though some implementations may specify a contract, e.g., TreeSet

Returns:
an iterator that provides access to elements from this set

unofficial documentation for the APCS Java Subset