1
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.

1
  • for (Object i : mylist) { System.out.println(i); } Commented May 21, 2018 at 10:12

3 Answers 3

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

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.