Java object in Arraylist or List

I want to know how I can use my ObjetTWS object with the parameter of my ObjectTWS() function. And how can I put an object in an Arraylist or 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 tried 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; 
+5
source share
5 answers

You have already defined the constructor:

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

This forces the JVM to omit the default constructor, so you must add it manually

 public ObjetTWS() {} 

Or declare an object with the given constructor:

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

Since you created your own constructor in your class with a parameter, the default constructor will not work at all, so you need to pass parameters using your constructor, and also initialize the list before adding an element to them.

+2
source

You must initialize the list first.

 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 to it.

Also try to keep your default constructor

Since you override it with an argument constructor

 public ObjectTWS() {} 
+1
source

By default, objects have less constructor with a parameter (which is the one you call in the second code snippet). This, however, is replaced by other constructors when you provide them, which you do in the first example.

To solve this problem, you have 2 options:

  • Add a less constructor parameter to the ObjetTWS class: public ObjeTWS() {} //Do any initialization here

  • In your second code example, use this: ObjetTWS obj = new ObjetTWS(p_nom, p_type, p_jobAmont, p_jobAval);

+1
source

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

What he tells us is that you have no constructor with no arguments.

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

 public ObjectTWS() { // Any code logic } 
0
source

All Articles