gpt4 book ai didi

java - 我如何使用 foreach 循环来打印不同类的不同对象的Arraylist

转载 作者:行者123 更新时间:2023-11-30 06:10:05 24 4
gpt4 key购买 nike

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));
}*/

}
}

My Arraylist is of diiferent object types and all have fields with values and a toString method in each class (so that the printing is possible).....If i dont use a loop and if i use an iterating loop its working fine but i want to use a for each loop i used the above syntax but its showing errors.

最佳答案

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

并且不要将 myList 声明为 ArrayList,而仅声明为 List - 更喜欢在可用时将变量声明为接口(interface)

关于java - 我如何使用 foreach 循环来打印不同类的不同对象的Arraylist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50446540/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com