21xrx.com
2025-03-31 02:38:01 Monday
文章检索 我的文章 写文章
使用JavaSet和Get方法实现数据存储和获取
2023-06-16 10:42:40 深夜i     11     0
JavaSet Get方法 数据存储

在Java中,使用Set和Get方法可以很方便地实现数据的存储和获取。下面我们来看一个简单的代码案例,演示如何使用JavaSet和Get方法。

代码案例:

import java.util.HashSet;
public class Student {
  private String name;
  private int age;
  public Student(String name, int age)
    this.name = name;
    this.age = 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;
  
  public static void main(String[] args) {
    HashSet
  students = new HashSet<>();
 
    students.add(new Student("张三", 18));
    students.add(new Student("李四", 20));
    students.add(new Student("王五", 22));
    for (Student s : students) {
      System.out.println("姓名:" + s.getName() + ",年龄:" + s.getAge());
    }
  }
}

在上面的代码中,我们定义了一个Student类,包含姓名和年龄两个属性,以及相应的Set和Get方法。我们还定义了一个HashSet集合,用于存储Student对象。在main方法中,我们分别添加了三个Student对象到集合中,并使用增强for循环遍历集合,输出每个学生的姓名和年龄。

通过这个案例,我们可以学习到如何使用JavaSet和Get方法实现数据存储和获取。

  
  

评论区