i汽车类
1 package com.lanxi.demo2_3; 2 public class Car { 3 private String name; 4 private int price; 5 @Override//重写toString方法 6 public String toString() { 7 return "Car [name=" + name + ", price=" + price + "]"; 8 } 9 public Car() {//创建无参构造方法 10 super(); 11 } 12 public Car(String name, int price) {//构造有参构造方法 13 super(); 14 this.name = name; this.price = price; 15 } 16 //创建get,set方法 17 public String getName() { 18 return name; 19 } 20 public int getPrice() { 21 return price; 22 } 23 }
测试类
1 package com.lanxi.demo2_3; 2 import java.util.HashSet; 3 import java.util.Iterator; 4 import java.util.Set; 5 public class Test { 6 public static void main(String[] args) { 7 Set set=new HashSet(); 8 Car car1=new Car("奔驰",26300); 9 Car car2=new Car("宝马",21300); 10 Car car3=new Car("东风",23500); 11 Car car4=new Car("奥迪",23400); 12 Car car5=new Car("奔驰",26300); 13 set.add(car1); 14 set.add(car2); 15 set.add(car3); 16 set.add(car4); 17 set.add(car5); 18 Iterator it=set.iterator(); 19 while(it.hasNext()){ 20 Car car=(Car) it.next(); 21 System.out.println(car); 22 System.out.println("降价后汽车价钱:"+(car.getPrice()-10000)); 23 } 24 } 25 }