日期:2014-05-20 浏览次数:20757 次
import java.util.*; public class java3 { public static void main(String[] agr){ class Cat extends Object{ private String name; private int age; public Cat(String name,int age ){ this.name =name; this.age=age; } public String toString() { return "cat name is " + name +",age is " + age; } } Set<Cat> m= new HashSet<Cat>(); m.add(new Cat("小黑",2)); m.add(new Cat("小花",1)); m.add(new Cat("小白",3)); // Iterator<Cat> it=m.iterator(); // while(it.hasNext()) // if(it.next().age>2) // it.remove(); for(Cat i:m) System.out.println(i); } }
------解决方案--------------------
package main; import java.util.*; public class Main { // 这种情况最好不要使用内部类 public static void main(String[] agr) { Set<Cat> m = new HashSet<Cat>(); m.add(new Cat("小黑", 2)); m.add(new Cat("小花", 1)); m.add(new Cat("小白", 3)); for (Cat i : m) System.out.println(i.getName() + i.getAge()); } } class Cat extends Object { private String name; private int age; public Cat(String name, int age) { this.setName(name); this.setAge(age); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
------解决方案--------------------
重写toString方法