/*Collection--HashSet,TreeSet*/
import java.util.*;
class Animal
{
String name;
int age;
Animal(String name,int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
class Cat extends Animal implements Comparable<Cat>//实现Comparable让元素具有比较性
{
Cat(String name,int age)
{
super(name,age);
}
public int hashCode()
{
return name.hashCode()+age*6;
}
public boolean equals(Object obj)
{
if(!(obj instanceof Cat))
throw new RuntimeException("不是Cat对象");
Cat cat = (Cat) obj;
return this.name.equals(cat.name) && this.age == cat.age;
}
public int compareTo(Cat c)
{
int num = this.name.compareTo(c.name);
if(num ==0)
return new Integer(age).compareTo(c.age);
return num;
}
}
class Dog extends Animal
{
Dog(String name,int age)
{
super(name,age);
}
public int hashCode()
{
return name.hashCode()+age*6;
}
public boolean equals(Object obj)
{
if(!(obj instanceof Dog))
throw new RuntimeException("不是dog对象");
Dog dog = (Dog) obj;
return this.name.equals(dog.name) && this.age == dog.age;
}
}
class Comp implements Comparator<Animal>//TreeSet集合比较器
{
public int compare(Animal a,Animal a2)
{
int num = new Integer(a.getAge()).compareTo(new Integer(a2.getAge()));
if(num ==0)
return a.getName().compareTo(a2.getName());
return num;
}
}
class AnimalSetTest
{
public static void main(String[] args)
{
HashSet<Cat> hs = new HashSet<Cat>();//HashSet集合元素无序,元素不可以重复,根据hashCode排序
hs.add(new Cat("小白猫",2));
hs.add(new Cat("小黑猫",3));
hs.add(new Cat("小灰猫",1));
hs.add(new Cat("大黑猫",4));
printHashSet(hs);
sop("---------------------------------");
TreeSet<Cat> ts = new TreeSet<Cat>();//TreeSet集合根据compareTo的返回值进行排序
ts.add(new Cat("小灰猫",1));//元素自身具备比较性,按照姓名排序
ts.add(new Cat("小黑猫",3));
ts.add(new Cat("小白猫",2));
ts.add(new Cat("大黑猫",4));
printTreeSet(ts);
sop("---------------------------------");
TreeSet<Dog> ds = new TreeSet<Dog>(new Comp());//第二种方法,使用比较器,按照年龄排序
ds.add(new Dog("大黄狗",4));
ds.add(new Dog("大灰狗",2));
ds.add(new Dog("大黑狗",3));
ds.add(new Dog("大白狗",1));
printTreeSet(ds);
}
public static void printHashSet(HashSet<? extends Animal> c)//HashSet集合迭代器
{
Iterator<? extends Animal> lt = c.iterator();
while(lt.hasNext())
{
Animal a = lt.next();
sop("AnimalName = "+a.getName()+" Age = "+a.getAge());
}
}
public static void printTreeSet(TreeSet<? extends Animal> c)//TreeSet集合迭代器
{
Iterator<? extends Animal> lt = c.iterator();
while(lt.hasNext())
{
Animal a = lt.next();
sop("AnimalName = "+a.getName()+"...Age = "+a.getAge());
}
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
|
|