package cn.bdqn.chatpterone.keben; import java.util.*; public class TestHanshSet { public static void main(String[] args) { //创建4个狗狗对象 Dog ououDog = new Dog("欧欧","雪瑞纳"); Dog yayaDog = new Dog("亚亚","拉布拉多"); Dog meimeiDog = new Dog("美美","雪瑞纳"); Dog feifeiDog = new Dog("菲菲","拉布拉多"); //2创建ArrayList集合对象并把4个狗狗对象放入其中 Set dogs = new HashSet(); dogs.add(ououDog); dogs.add(yayaDog); dogs.add(meimeiDog); //dogs.add(2,feifeiDog); //输出集合中狗狗的数量 System.out.println("共计有"+dogs.size()+"条狗狗"); //通过遍历集合显示各条狗狗信息 System.out.println("分别是:"); System.out.println("***********************"); //删除狗狗操作 dogs.remove(0); dogs.remove(meimeiDog); for (Object object : dogs) { System.out.println(((Dog) object).getName()+((Dog) object).getStrain()); } //两个都可以遍历 for (Dog object : dogs) { System.out.println(object.getName()+object.getStrain()); } System.out.println("***********************"); if(dogs.contains(meimeiDog)){ System.out.println("集合中包含美美信息"); } else{ System.out.println("集合中不包含美美信息"); } } }
因为HashSet没有get方法,无法得到数组元素的值,只能通过加强for循环
下面是我定义的Dog类
package cn.bdqn.chatpterone.keben; public class Dog extends Pet{ private String strain; /** * 有参构造方法 * @param name 昵称 * @param strain 性别 */ public Dog(String name,String strain){ super(name); //super(name); this.strain = strain; } public String getStrain(){ return strain; } public void print(){ super.print(); System.out.println("我是一只"+this.strain+"。"); } } package cn.bdqn.chatpterone.keben; public class Pet { /** * 宠物类、狗狗类和企鹅类 */ private String name = "无名氏"; private int health = 100; private int love = 0; /** * 无参构造方法 */ public Pet(){ health = 95; System.out.println("执行宠物的无参构造方法"); } /** * 有参的构造方法 */ public Pet(String name){ this.name = name; } public String getName(){ return name; } public int getHealth(){ return health; } public int getLove(){ return love; } /** * 输出宠物信息 */ public void print(){ System.out.println("宠物的自白: 我的名字叫:"+this.name+",我的健康值是"+this.health+"我" + "和主人的亲密度是"+this.love); } }