gpt4 book ai didi

java : Parsing An ArrayList and setting them into a Object

转载 作者:行者123 更新时间:2023-11-29 06:42:41 24 4
gpt4 key购买 nike

我有这两个类:

class Student
{
String name;
String age ;
}

class Person
{

String name;
String age ;
String grade ;
}

在下面的代码中,我创建了 Student 对象并将它们设置在 ArrayList 中。在 ArrayList 中设置数据后,我需要解析该 ArrayList 并在另一个对象中设置值:

public class Work {

public static void main(String args[]) {

List StudentItems = new ArrayList();

Student stud1 = new Student();
Student stud2 = new Student();

stud1.name = "ABC";
stud1.age = "28";
stud2.name = "XYZ";
stud2.age = "38";

StudentItems.add(stud1);
StudentItems.add(stud2);

Person[] pers = new Person[StudentItems.size()];

for (int i = 0; i < StudentItems.size(); i++) {
pers[i] = new Person();

// I am confused here , could anyone please help

}

}
}

最佳答案

尝试一下。这将完成工作

你的 Person 类应该是这样的:

package com.student.person.work;

/**
*
* @author sarath_sivan
*/
public class Person {

private String name;
private int age;
private String grade;

public String getName() {
return this.name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return this.age;
}

public void setAge(int age) {
this.age = age;
}

public String getGrade() {
return this.grade;
}

public void setGrade(String grade) {
this.grade = grade;
}

}

你的学生类应该是这样的:

package com.student.person.work;

/**
*
* @author sarath_sivan
*/
public class Student {

private String name;
private int age;

public String getName() {
return this.name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return this.age;
}

public void setAge(int age) {
this.age = age;
}

}

最后,Work 类:

package com.student.person.work;

import java.util.ArrayList;
import java.util.List;

/**
*
* @author sarath_sivan
*/
public class Work {

public static String calculateGrade() {
String grade = "";
// Your code to find the grade.
//............
return grade;
}

public static void doWork() {
List<Student> studentList = new ArrayList<Student>();

Student student = new Student();
student.setName("ABC");
student.setAge(24);
studentList.add(student);

student = new Student();
student.setName("DEF");
student.setAge(28);
studentList.add(student);

student = new Student();
student.setName("GHI");
student.setAge(21);
studentList.add(student);

List<Person> personList = new ArrayList<Person>();

for(Student students : studentList) {
Person person = new Person();
person.setName(students.getName());
person.setAge(students.getAge());
person.setGrade(Work.calculateGrade());// Setting the grade
}
}

public static void main(String[] args) {
Work.doWork();
}

}

希望这会有所帮助。

谢谢!

关于java : Parsing An ArrayList and setting them into a Object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9562150/

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