简体   繁体   中英

Java object in Arraylist or List

I want to know how I can use my object ObjetTWS with the parameter of my function ObjectTWS() . And how I can put the object in a Arraylist or a List .

public class ObjetTWS {

    String nom; 
    List<String> jobAmont; 
    List<String> jobAval; 
    String type;


    public ObjetTWS(String p_nom, String p_type,String p_jobAmont,String p_jobAval){

I already try this but it says ObjetTWS undefined :

ObjetTWS obj  = new ObjetTWS();

obj.nom = p_nom;
obj.jobAmont.add(p_jobAmont);
obj.jobAval.add(p_jobAval);
obj.type = p_type;

You already defined a constructor:

public ObjetTWS(String p_nom, String p_type,String p_jobAmont,String p_jobAval){

That makes the JVM to omit the default constructor, so you must add it manually

public ObjetTWS() {}

Or declare object with given constructor:

ObjetTWS obj = new ObjetTWS(p_nom, p_type,p_jobAmont, p_jobAval);

由于您已使用参数在类中创建了自己的构造函数,因此默认构造函数根本不起作用,因此您必须使用构造函数传递参数,并在向元素添加元素之前初始化List。

First you should initialize the list

public class ObjetTWS {   
    String nom; 
    List<String> jobAmont = new ArrayList<String> (); 
    List<String> jobAval =  new ArrayList<String> (); 
    String type;

Then you try to add elements into it.

And also try to keep your default constructor

As you are overriding it by arguments constructor

public ObjectTWS() {}

By default, objects have a parameter less constructor (which is the one you are calling in your second code snippet). This however, gets replaced with other constructors when you provide them, which is what you are doing in your first example.

To solve this problems, you have 2 options:

  1. Add a parameter less constructor in your ObjetTWS class: public ObjeTWS() {} //Do any initialization here

  2. In your second code sample, use this: ObjetTWS obj = new ObjetTWS(p_nom, p_type, p_jobAmont, p_jobAval);

public ObjetTWS(String p_nom, String p_type,String p_jobAmont,String p_jobAval) what you have here is a parameterized constructor. However in the code you are trying to do this ObjetTWS obj = new ObjetTWS();

What it tell us is that you don't have a constructor with no arguments.

So, to be able to do this, you need to add another constructor to your class, which should look like this :

public ObjectTWS() {
    // Any code logic
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM