我怎样才能为每个循环使用a来打印不同类别的不同对象的Arraylist

时间:2018-05-21 10:11:36

标签: java class object arraylist tostring

class Main
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);

        Loan loan = new Loan();
        Date date = new Date();
        Strings strings = new Strings();
        Frame frame = new Frame();
        Circle circle = new Circle();

        ArrayList<Object> mylist = new ArrayList<Object>();
        mylist.add(loan);
        mylist.add(date);
        mylist.add(strings);
        mylist.add(frame);
        mylist.add(circle);

        for (Object i : mylist)
        {
            System.out.println(mylist.get(i));
        }
         /*
         //this method is working fine
         System.out.println(mylist.get(0));
         System.out.println(mylist.get(1));
         System.out.println(mylist.get(2));
         System.out.println(mylist.get(3));
         System.out.println(mylist.get(4));

         //this method is also working fine
         for (int i = 0; i < 4; i++)
         {
            System.out.println(mylist.get(i));
         }*/

    }
}
  

我的Arraylist是不同的对象类型,并且每个类都有值的字段和toString方法(以便打印是可能的).....如果我不使用循环并且如果我使用迭代循环其工作正常,但我想为每个循环使用一个我使用上面的语法,但它显示错误。

3 个答案:

答案 0 :(得分:1)

myList.forEach(System.out::println); 

并且不要将myList声明为ArrayList,而是仅将List声明为 - 只要可用时将变量声明为接口

答案 1 :(得分:0)

更改

var client = new FabricClient();
await client.ServiceManager.DeleteServiceAsync(new DeleteServiceDescription(Context.ServiceName));

    for (Object i : mylist)
    {
        System.out.println(mylist.get(i));
    }
for (Object i : mylist) { System.out.println(i); } 循环中的

i是对象本身而不是索引。

答案 2 :(得分:0)

这里:

for (Object i : mylist)
{
    System.out.println(mylist.get(i)); 
                                  ^----- error here
}

您使用myList.get()变量作为参数调用Object 它在编译时无效,因为ArrayList.get()int作为参数:

  

E java.util.ArrayList.get(int index)

在某种程度上,你混合了foreach和&#34; basic for&#34;语法。
&#34;基本为&#34;声明需要使用索引:

for (int i=0; i<mylist.size(); i++) {
     System.out.println(myList.get(i)); 
}

但foreach语法简化了:

for (Object i : mylist) {
     System.out.println(i); 
}