Создать класс при помощи SortedSet (Beer)Добавлено (2011-12-04, 17:31:20)
---------------------------------------------
Есть такой вариант
Code
import java.util.Comparator;
import java.util.SortedSet;
import java.util.TreeSet;
public class TestBeer {
public static void main(String[] args) {
SortedSet parts = new TreeSet ();
parts.add(new Beer("Stella Artua", 1000));
parts.add(new Beer("Obolon", 4562));
parts.add(new Beer("Slavutich", 9912));
parts.add(new Beer("Rogan", 1512));
System.out.println(parts);
SortedSet <String> sortByDescription = new TreeSet<String>(new Comparator()
{
public int compare(Object a, Object b)
{
Beer itemA = (Beer)a;
Beer itemB = (Beer)b;
String descrA = itemA.getDescription();
String descrB = itemB.getDescription();
return descrA.compareTo(descrB);
}
});
sortByDescription.addAll(parts);
System.out.println(sortByDescription);
}
}
class Beer implements Comparable {
public Beer (String aDescription, int aVolume)
{
description = aDescription;
volume = aVolume;
}
public String getDescription()
{
return description;
}
public String toString()
{
return "[descripion=" + description
+ ", volume=" + volume + "]";
}
public boolean equals(Object other)
{
if (getClass() == other.getClass())
{ Beer otherBeer = (Beer)other;
return description.equals(otherBeer.description)
&& volume == otherBeer.volume;
}
else
return false;
}
public int hashCode()
{
return 13 * description.hashCode() + 17 * volume;
}
public int compareTo(Object other)
{
Beer otherItem = (Beer)other;
return volume - otherItem.volume;
}
private String description;
private int volume;
}