javaarraylistprintln

print Arraylist without loop


I want to print elements in my Arraylist without using a loop of any kind is that possible in java?

import java.util.ArrayList;

class Person
{
    String name;
    String role;

    public Person(String name, String role)
    {
        this.name = name;
        this.role = role;
    }
}

class Main
{
    public static void main(String[] args)
    {
        Person person1 = new Person("george","programmer");
        Person person2 = new Person("barack","programmer");
        Person person3 = new Person("ismail","programmer");

        ArrayList <Person> people = new ArrayList <Person>();
        people.add(person1);
        people.add(person2);
        people.add(person3);

        System.out.println(people.get(0));
        System.out.println(people.get(1));
        System.out.println(people.get(2));
    }
}

Solution

  • You can print one by one without using loop but the problem is because you are using object type so you cannot print objects unless you use a toString method in the class even if you don’t use Arraylist it wont work if you want to print object, unless you use toString method

        class Main
        {
            public static void main(String[] args)
            {  
                ArrayList<Integer> arrayList = new ArrayList<Integer>();
                arrayList.add(6);
                arrayList.add(3);
                arrayList.add(5);
    
                System.out.println(arrayList.get(0));
                System.out.println(arrayList.get(1));
                System.out.println(arrayList.get(2));
            }
        }