This program sorts a set of item by comparing their descriptions
/*
This program is a part of the companion code for Core Java 8th ed.
(http://horstmann.com/corejava)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
@version 1.10 2004-08-02
@author Cay Horstmann
*/
import java.util.Comparator;
import java.util.SortedSet;
import java.util.TreeSet;
/**
This program sorts a set of item by comparing
their descriptions.
*/
public class TreeSetTest
{
public static void main(String[] args)
{
SortedSet<Item> parts = new TreeSet<Item>();
parts.add(new Item("Toaster", 1234));
parts.add(new Item("Widget", 4562));
parts.add(new Item("Modem", 9912));
System.out.println(parts);
SortedSet<Item> sortByDescription = new TreeSet<Item>(new
Comparator<Item>()
{
public int compare(Item a, Item b)
{
String descrA = a.getDescription();
String descrB = b.getDescription();
return descrA.compareTo(descrB);
}
});
sortByDescription.addAll(parts);
System.out.println(sortByDescription);
}
}
/**
An item with a description and a part number.
*/
class Item implements Comparable<Item>
{
/**
Constructs an item.
@param aDescription the item's description
@param aPartNumber the item's part number
*/
public Item(String aDescription, int aPartNumber)
{
description = aDescription;
partNumber = aPartNumber;
}
/**
Gets the description of this item.
@return the description
*/
public String getDescription()
{
return description;
}
public String toString()
{
return "[descripion=" + description
+ ", partNumber=" + partNumber + "]";
}
public boolean equals(Object otherObject)
{
if (this == otherObject) return true;
if (otherObject == null) return false;
if (getClass() != otherObject.getClass()) return false;
Item other = (Item) otherObject;
return description.equals(other.description)
&& partNumber == other.partNumber;
}
public int hashCode()
{
return 13 * description.hashCode() + 17 * partNumber;
}
public int compareTo(Item other)
{
return partNumber - other.partNumber;
}
private String description;
private int partNumber;
}
Related examples in the same category