标签:print div port 创建 ret ash etag false java
自定义一个Student对象类
代码:
1 import java.util.Objects; 2 3 public class Student { 4 private String name; 5 private int age; 6 7 public Student(String name, int age) { 8 this.name = name; 9 this.age = age; 10 } 11 12 public String getName() { 13 return name; 14 } 15 16 public void setName(String name) { 17 this.name = name; 18 } 19 20 public int getAge() { 21 return age; 22 } 23 24 public void setAge(int age) { 25 this.age = age; 26 } 27 28 @Override 29 public boolean equals(Object o) { 30 if (this == o) 31 return true; 32 if (o == null || getClass() != o.getClass()) 33 return false; 34 Student student = (Student) o; 35 return age == student.age && 36 Objects.equals(name, student.name); 37 } 38 39 @Override 40 public int hashCode() { 41 return Objects.hash(name, age); 42 } 43 }
使用HashSet存储对象
代码:
1 import java.util.HashSet; 2 public class test { 3 public static void main(String[] args) { 4 //创建集合对象 该集合中存储 Student类型对象 5 HashSet<Student> students = new HashSet<>(); 6 //存储 7 Student stu1 = new Student("王健林", 50); 8 Student stu2 = new Student("马化腾", 40); 9 Student stu3 = new Student("王云", 30); 10 students.add(stu1); 11 students.add(stu2); 12 students.add(stu3); 13 /* 结果: 14 王云的年龄是30 15 王健林的年龄是50 16 马化腾的年龄是40*/ 17 for(Student student : students){ 18 System.out.println(student.getName()+"的年龄是"+student.getAge()); 19 } 20 21 22 } 23 }
标签:print div port 创建 ret ash etag false java
原文地址:https://www.cnblogs.com/0error0warning/p/12528387.html