无法将项目添加到 arrayList

Can't add an item to arrayList

我目前遇到一个问题,我概述了我的构造函数的参数以及我希望它接收的内容。但是尝试通过 ArrayList 添加元素时,我不断收到一条错误消息 "identifier expected" .对我做错了什么有什么想法吗?

Employer.java:

public class Employer {

    private String name;
    private String email;
    private String password;
    private Employees employees;
    private STP stp;


     Employer(String name, String email, String password){
         this.name = name;
         this.email = email;
         this.password = password;
     }           
}

Employers.java:

import java.util.ArrayList;

public class Employers {

    private ArrayList<Employer> employers = new ArrayList<Employer>();
    
    employers.add("John Smith", "john.smith@example.com", "super123");
}

我只是想弄清楚我做错了什么,或者我是否采取了错误的方法。

您需要明确键入 class

employers.add(new Employer("John Smith", "john.smith@example.com", "super123"));

PS 这需要在代码块中

  package com.java.avee;

  import java.util.ArrayList;

  public class Employers {

  public static void main(String args[]){
   ArrayList<Employer> employers = new ArrayList<Employer>();
   employers.add(new Employer("John Smith", "john.smith@example.com", 
  "super123"));
 }
}

class Employer {
private String name;
private String email;
private String password;

 Employer(String name, String email, String password){
     this.name = name;
     this.email = email;
     this.password = password;
 }           
}

您似乎错过了在将 employer 添加到 arrayList 之前创建它的对象。

在这里您使用的是泛型。因此,您只能添加 Employer 对象或 Employer class.

的子对象 class

private ArrayList < Employer> employers = new ArrayList();
employers.add("John Smith", "john.smith@example.com", "super123");

您的雇主是 ArrayList 类型的 Employer。因此,当您尝试在雇主列表中添加内容时,它会期望 Employer 类型的内容。 但是,在你的第二行中,你试图添加一些用逗号分隔的字符串。这就是您将无法添加的原因。 相反,您必须先构建 Employee 对象,然后像下面这样添加:

Employer employer= new Employer("John Smith", "john.smith@example.com", "super123");
employers.add(employer); //here employer is an object of Employer type

此外,我看到你覆盖了构造函数,所以在你的 Employer class:

中也定义了默认构造函数
Employer(){};