Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 678
Subas Avatar asked May 19 '15 07:05

Subas


3 Answers

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);
like image 72
Jordi Castilla Avatar answered Sep 18 '22 14:09

Jordi Castilla


Since you have created a constructor of your own in your class with parameter so default constructor will not work at all, so you must have to pass the parameters with your constructor and also initialize the List before adding element to them.

like image 27
sumit Avatar answered Sep 21 '22 14:09

sumit


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);

like image 28
npinti Avatar answered Sep 22 '22 14:09

npinti