0

I have made an arraylist in one class but when I pass it to another class it is empty. There are elements in one class but in another class it is empty.

Here is my code in one class.

System.out.println(mot);
Paint p=new Paint(mot, start );

Here is my code in another class

ArrayList<String> motif;
ArrayList<Integer> number;
NewJFrame j=new NewJFrame();

public Paint(ArrayList<String> motif,ArrayList<Integer> number) {
   initComponents();
   motif=new ArrayList();
   number=new ArrayList<>();
   j=new NewJFrame();
}

public void paint(Graphics g) {
   System.out.print(j.mot);
}

Please tell me how to solve my problem of empty arraylist?

3
  • 1
    What exactly is the problem? Where do you use motif or number? What is j.mot or just mot? Commented Dec 5, 2013 at 7:53
  • motif=new ArrayList(); will make the passed arraylist motif to be new instance of arraylist, and thus since its new , its empty. Commented Dec 5, 2013 at 7:56
  • I have not use motif or number. Mot is string arraylist in another class (NewJFrame). When I call it in another class i-e with j.mot it gives me empty arraylist. Commented Dec 5, 2013 at 7:59

5 Answers 5

2

change these lines of code:

motif=new ArrayList();
number=new ArrayList<>();

to

this.motif = motif;
this.number = number;
Sign up to request clarification or add additional context in comments.

Comments

1

This two lines make new instance of listes, try to change them:

motif=new ArrayList();
number=new ArrayList<>();

This would be better:

this.motif = motif;
this.number = number;

Comments

1

Try addAll:

 public Paint(ArrayList<String> pMotif,ArrayList<Integer> pNumber) {
    initComponents();
    motif=new ArrayList();
    motif.addAll(pMotif); //use addAll 
    number=new ArrayList<>();
    motif.addAll(pNumber); //use addAll 

Comments

1

You're overwriting the copies of motif and number you got with new (empty) versions in these lines

motif=new ArrayList();
number=new ArrayList<>();

If you want to set your class members to an empty ArrayList, refer to them with this:

this.motif = new ArrayList();
this.number = new ArrayList<>();

If you want to set them to the ArrayLists passed in, do this:

this.motif = motif;
this.number = number;

Another option would be copying the values from the ArrayLists passed in:

this.motif = new ArrayList(motif);
this.number = new ArrayList<>(number);

Comments

1

you are passing the value to another class, so you should tell your compiler to use current object i.e this object.....

you are assigning the values using Constructor So, alwayz use either "this" or "super" ( which is first statement in Constructor )

use

this.motif = motif; this.number = number;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.