gpt4 book ai didi

java - Java 类中的硬编码 Java 列表

转载 作者:行者123 更新时间:2023-12-01 23:06:01 27 4
gpt4 key购买 nike

我正在对对象 Student 的列表项进行一些测试,但是我更喜欢在 java 类对象中创建硬编码列表,然后从那里提取数据,而不是连接到数据库并在结果集中选择记录。然而,自从我这样做以来已经很长时间了,我想我没有准确地写下类(class)。

我希望每次调用此类或实例化它时都能返回硬编码列表。下面是类(class)。我需要一些帮助来设置硬编码列表。

学生类

public class Student {

private int studentId;
private String studentLastname;
private String studentFirstName;
private int studentAge;


public Student() {

}
public Student(int studentId, String studentLastname,
String studentFirstName, int studentAge) {

this.studentId = studentId;
this.studentLastname = studentLastname;
this.studentFirstName = studentFirstName;
this.studentAge = studentAge;
}
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getStudentLastname() {
return studentLastname;
}
public void setStudentLastname(String studentLastname) {
this.studentLastname = studentLastname;
}
public String getStudentFirstName() {
return studentFirstName;
}
public void setStudentFirstName(String studentFirstName) {
this.studentFirstName = studentFirstName;
}
public int getStudentAge() {
return studentAge;
}
public void setStudentAge(int studentAge) {
this.studentAge = studentAge;
}


}

数据

我想插入以下数据

 Student.add(1, "john","william", 20);
Student.add(2, "bob","elis", 25);
Student.add(3, "harry","potter", 19);
Student.add(4, "micheal","louis", 20);
Student.add(5, "smith","sobers", 30);

最佳答案

对此有很多选择。人们甚至可以建议使用依赖注入(inject)框架来指定“学生来源”的特定实现。然而,在最简单的情况下,它可能看起来像这些方法之一......

class StudentUtils
{
public static List<Student> getDummyList(int n)
{
List<Student> list = new ArrayList<Student>();
for (int i=0; i<n; i++)
{
list.add(new Student(i, "Last"+i, "First"+i, 20+(i%10)));
}
return list;
}

public static List<Student> getDummyList()
{
List<Student> list = new ArrayList<Student>();
list.add(new Student(0, "Foo", "Bar", 20));
list.add(new Student(1, "Fee", "Bur", 30));
list.add(new Student(2, "Faa", "Bir", 40));
return list;
}
}

关于java - Java 类中的硬编码 Java 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22736539/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com