Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass ArrayList to another Class

I'm having some Trouble with an ArrayList. All i need to do is to pass a filled ArrayList to another Class so i can use the Values of the ArrayList there. Here's a snippet from the first Class:

public ArrayList<String> collCollect = new ArrayList<String>();
for (int i = 0; i < ListModel.size(); i++) {
        collCollect.add(ListModel.get(i).toString());
    }
    System.out.println(collCollect);

Till this Part everything is going quite well (i stripped the rest of the Code!)

Now comes the tricky Part! This is the Second Class:

ClassA pMain;
DecimalFormat f = new DecimalFormat("#0.00");
public ArrayList<String> listContent = new ArrayList<String>(pMain.collCollect);
DefaultListModel<String> ListModelNew = new DefaultListModel<String>();

public static void main(String args[]) {
for (int i = 0; i < listContent.size(); i++){
        ListModelNew.add(i, listContent.get(i));
    } 
}

Everytime the ClassB is loaded i get a NullPointerException from the Line where the reference to the Array in pMain is made.

Any help would be appriciated...i'm unable to get the Values from ClassA ArrayList to ClassB -.-

like image 595
ZeroGS Avatar asked Dec 06 '25 00:12

ZeroGS


2 Answers

ClassA pMain; // here you not initialized the object.

pMain.collCollect // here you are getting the NullpointerException

public ArrayList<String> listContent = new ArrayList<String>(pMain.collCollect);
                                                                    ^__see here   

change

ClassA pMain;

to

ClassA pMain = new ClassA ();
like image 193
Prabhakaran Ramaswamy Avatar answered Dec 08 '25 14:12

Prabhakaran Ramaswamy


An instance of ClassA needs to be created in the second class. I would recommend creating it within the main method so ClassA is not a dependency for the second class.

DecimalFormat f = new DecimalFormat("#0.00");
public ArrayList<String> listContent; 
DefaultListModel<String> ListModelNew = new DefaultListModel<String>();

public static void main(String args[]) {
ClassA pMain = new ClassA();
listContent = new ArrayList<String>(pMain.collCollect);
for (int i = 0; i < listContent.size(); i++){
        ListModelNew.add(i, listContent.get(i));
    } 
}

This can be further refactored:

DecimalFormat f = new DecimalFormat("#0.00");
DefaultListModel<String> ListModelNew = new DefaultListModel<String>();

public static void main(String args[]) {
ClassA pMain = new ClassA();
for (int i = 0; i < pMain.collCollect.size(); i++){
        ListModelNew.add(i, pMain.collCollect.get(i));
    } 
}
like image 21
Kevin Bowersox Avatar answered Dec 08 '25 13:12

Kevin Bowersox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!