如何从main()调用类中的集合参数化方法

时间:2016-08-31 09:12:57

标签: java arraylist

我正在用集合(ArrayList)编写java程序。我对来自main()的函数调用存有疑问。因为该函数具有ArrayList对象作为参数。如何为方法的集合参数创建函数调用?

MainClass.java

public class MainClass {
    public static void main(String[] args) throws Exception{
     SecondClass obj = new SecondClass();
     obj.func();
     obj.func2(??????);//receives arraylist obj as parameter and print the values of that object
     }
}

SecondClass.java

class SecondClass{
   List<classname> func(){
      List<classname> result = new ArrayList<classname>();
       ...
       ..
       return result;
      }
   void func2(List<classname> result){
       //how to print the 'result'

       //for( classname  results: result) {
       //   System.out.println(results);
       //}
   }

}

如何从main()调用func2()并打印List对象&#39;结果&#39;?

2 个答案:

答案 0 :(得分:0)

public class MainClass {
    public static void main(String[] args) throws Exception{
     SecondClass obj = new SecondClass();
List<classname> listObj = obj.func();
     obj.func2(listObj);//receives arraylist obj as parameter and print the values of that object
     }
}

在此处,listObj填充了方法func返回的值。因此,同样可以作为参数传递给func2

答案 1 :(得分:0)

检查一下。

   public class MainClass {
    public static void main(String[] args) throws Exception{
     SecondClass obj = new SecondClass();

    List <classname> listOfSecondClass= obj.func();
     obj.func2(listOfSecondClass);
     }
}