Collections: Sets

 

Python

Java

 

A set is a mutable collection of 0 or more unique objects of any type.

 

The len function returns the number of elements in a set.

 

The set class includes many useful methods for insertions, removals, searches, and so forth.

 

set1 = set()

for x in range(10):

    set1.add(x)

 

for x in set1: print(x)

 

set2 = set([1,2,3])

 

set3 = set1.intersection(set2)

 

 

 

 

 

A set is a mutable collection of 0 or more unique objects of any type.  A generic set constrains its elements to the same supertype.

 

The Set interface includes the methods common to all implementing classes.  The SortedSet interface extends the Set interface to include methods for sorted sets. 

 

The implementing classes include HashSet and TreeSet.  A TreeSet can return its elements in sorted order.  Thus, it also implements the SortedSet interface.

 

A generic set specifies the element type of the set variable and the instantiated set object, as follows:

 

Set<String> names = new HashSet<String>();

SortedSet<Integer> ints = new TreeSet<Integer>();

 

Example:

 

// Add 10 random ints between 1 and 10

for (int i = 1; i <= 10; i++)

    ints.add((int)(Math.random() * 10 + 1));

 

// Print all elements in sorted order

for (int element : ints)

    System.out.println(element);

 

Note the use of a for loop to access the elements of a set.

 

A set can also be created from a list, as follows:

 

Set<String> names = new HashSet<String>(listOfNames);

 

Java collections typically include a constructor that accepts another collection as an argument and adds its elements to the newly instantiated collection.

 

 

Previous

Index

Next