Dedicated User
Dedicated User

Reputation: 97

How can i use a for each loop to print an Arraylist of different objects of different classes

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.

Upvotes: 1

Views: 2688

Answers (3)

davidxxx
davidxxx

Reputation: 131324

Here :

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

You invoke myList.get() with an Object variable as argument.
It is not valid at compile time as ArrayList.get() takes an int as parameter :

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

In a some way you mix the foreach and the "basic for" syntax.
The "basic for" statement requires the use of the index :

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

But the foreach syntax simplifies that :

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

Upvotes: 0

Honza Zidek
Honza Zidek

Reputation: 19916

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

and do not declare myList as ArrayList, but as List only - prefer declaring variables as interfaces whenever available

Upvotes: 1

Shanu Gupta
Shanu Gupta

Reputation: 3797

Change

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

to

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

i in foreach loop is the object itself not the index.

Upvotes: 0

Related Questions