黑马程序员技术交流社区
标题:
有没有办法让Iterator实现多个集合
[打印本页]
作者:
赵晓东
时间:
2012-12-21 16:32
标题:
有没有办法让Iterator实现多个集合
本帖最后由 Object 于 2013-1-23 16:50 编辑
/*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);
}
}
复制代码
作者:
Kevin123
时间:
2012-12-21 19:30
用增强for循环可以实现:
如下:
List<Animals> list;
for(Object o:list){
system.out.println(o.toString);
system.out.println(o.getName());
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2