简体   繁体   中英

how to pass an object from one main method to a main method in another class

I have two classes sum and f , and want to use an ArrayList ( ac ) from sum main method in f main method.

class sum

package pack;

import java.util.ArrayList;
import java.util.Iterator;

class sum {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ArrayList < String > ac = new ArrayList < String > ();
        ac.add("hai");
        ac.add("hw");
        ac.add("ai");
        ac.add("hi");
        ac.add("hai");
        Iterator it = ac.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}

class f

package pack;

import java.util.ArrayList;    
import pack.sum;

public class f extends sum {
    public static void main(String[] args) {    
        //here is use the ac object of array list
    }
}

Change Sum class a little bit

 class Sum {

        public ArraryList<String> main() {
            // TODO Auto-generated method stub
             ArrayList<String> ac= new ArrayList<String>();
                ac.add("hai");
                ac.add("hw");
                ac.add("ai"); 
                ac.add("hi"); 
                ac.add("hai");
                Iterator it=ac.iterator();
                while(it.hasNext()) 
                {    
                    System.out.println(it.next()); 
                 }

                  return ac;
               }

    }

Now change your f class like this

public class f extends sum {


    public static void main(String[] args) {


     ArrayList<String> ac = new Sum().main();
   // now you can use ac
    }

}

You can't have two main class, you can add one method in sum class to add arrayList logic as below :

class sum {

     public ArrayList<String> getList()
     {
            ArrayList<String> ac= new ArrayList<String>();
            ac.add("hai");
            ac.add("hw");
            ac.add("ai"); 
            ac.add("hi"); 
            ac.add("hai");
            Iterator it=ac.iterator();
            while(it.hasNext()) 
            {    
                System.out.println(it.next());  }
           }
     return ac;

}

And in the f class just create the object and call the method:

Sum obj = new Sum();
ArrayList<String> list = obj.getList();

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