簡體   English   中英

將一個類的對象添加到另一個類的ArrayList中

[英]Adding objects of a class to an ArrayList in another class

我試圖將一個名為Student的類的對象添加到另一個名為StudentClass的類的Arraylist中。 我已經初始化了列表,但是在解決如何向ArrayList添加對象時遇到了麻煩

學生班代碼

public class StudentClass
{
   List<Student> studentList;
   private String studentName;
   private int lengthOfString;

   public StudentClass()
   {
      super();
      studentList = new ArrayList<>();
   }

 public void addStudent(String aName)
   {
     String objt = new String(name, mark);
     studentList.add(Student);
   }

學生代碼

public class Student
{

    private String name;
    private int mark;


    public Student(String aName)
    {
       super();
       this.name = aName;
       this.mark = -1;   

嘗試這個:

 public void addStudent(String aName) {
     studentList.add(new String(aName));
 }

此外,Student類的構造函數也不接受標記作為第二個參數,至少不接受您發布的代碼。

似乎您的錯誤在這里:

 String objt = new String(name, mark);
 studentList.add(Student);

改寫這個:

 Student objt = new Student(name, mark);
 studentList.add(objt);

您需要創建一個新的Student對象,然后將其添加到列表中:

public void addStudent(String aName) {
     Student student = new Student(aName);
     studentList.add(student);
}

從您提供的代碼中並不清楚如何設置mark字段,但是可以將其傳遞給Student結構和/或添加getter和setter。

這應該工作。

  import java.util.*;
  public class StudentClass
  {
  List<Student> studentList;
  private String studentName;
  private int lengthOfString;

  public StudentClass()
  {
  super();
  studentList = new ArrayList<>();
  }

  public void addStudent(String aName) {
  Student student = new Student(aName);
  studentList.add(student);
  }      
  }

  public class Student
  {

  private String name;
  private int mark;

  public Student(String aName)
  {
  super();
  this.name = aName;
  this.mark = -1;   
  }
  }

我不清楚您打算如何處理商標?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM