Set

java.util.Set extends Collection, Iterable

Set is an interface and modelled after the mathematical set. Nulls may be prohibited. Duplicates​ are not allowed.

Primary implementation classes are TreeSet and HashSet.

TreeSet stores elements in sorted order. HashSet does not.

Because of ordering, the TreeSet may run slower than the HashSet.

Between the ordering of the elements and the efficiency of access, a trade-off maybe made depending on the requirement.

Adding null to TreeSet throws NullPointerException. Adding null to HashSet does not.

Methods
A few methods are shown below:

  • Object[] toArray()
  • boolean contains(Object o)
  • boolean addAll(Collection c)

Note
boolean equals(Object o) and hashCode() are related. As per the specification, if equals returns true, then the hashCode must also be the same for both the comparing objects.

An example
Point of sale
– Product, with equals and hashCode override
– Add to cart, prevents duplicates

// Product.java
package pos;
import java.math.*;
import java.util.*;

public class Product
{
	private String id;
	private String name;
	private BigDecimal price;
	private int quantity;
	
	public Product(String name, int quantity, double price) {
		this.name = name;
		this.quantity = quantity;
		this.price = BigDecimal.valueOf(price);
		this.id = uid();
	}

	@Override
	public boolean equals(Object obj)
	{
		return this.id.equals(((Product)obj).getId());
	}

	@Override
	public int hashCode()
	{
		return id.hashCode();
	}
	
	private String uid() {
		// String lUUID = String.format("%040d", new BigInteger(UUID.randomUUID().toString().replace("-", ""), 16));
		UUID uid = UUID.randomUUID();
		String uidStr = uid.toString();
		// remove hiphens
		uidStr = uidStr.replace("-", "");
		BigInteger bigI = new BigInteger(uidStr, 16);
		String uids = String.format("%040d", bigI);
		return uids;
	}

	@Override
	public String toString()
	{
		return id;
	}

	
	public void setId(String id)
	{
		this.id = id;
	}

	public String getId()
	{
		return id;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	public String getName()
	{
		return name;
	}

	public void setPrice(BigDecimal price)
	{
		this.price = price;
	}

	public BigDecimal getPrice()
	{
		return price;
	}

	public void setQuantity(int quantity)
	{
		this.quantity = quantity;
	}

	public int getQuantity()
	{
		return quantity;
	}
}

// Cart.java
package pos;
import java.util.*;

public class Cart
{
	private static Set<Product> items = new HashSet<>();
	private static void showItems() {
		Iterator<Product> it = items.iterator();
		while(it.hasNext()) {
			System.out.println(it.next());
		}
	}
	public static void main(String[] args) {
		Product router = new Product("D-Link",25, 4565.0);
		Product cable = new Product("Ethernet",32,45.75);
		Product hub = new Product("D-Link",25, 4565.0);
		items.add(router);
		items.add(cable);
		items.add(hub);
		items.add(router);
		showItems();
	}
}

Exercise
Rewrite the random numbers example from the Arrays post using the Set.

Author: Anand Betanabhotla

Corporate Trainer

Leave a comment