-2

I have an arraylist filled with different variables. How can I print this arraylist out to the console using the printf flag in Java?

public class mendietaRAL {
    public static void theArrayList() {
        ArrayList<Object> theList = new ArrayList<Object>();

        theList.add(123);
        theList.add("Java");
        theList.add(3.75);
        theList.add("Summer C");
        theList.add(2018);

        for (int i = 0; i < theList.size(); i++) {
            System.out.printf(theList.get(i));
        }


        theList.remove(1);
        theList.remove(3);

        System.out.println();

        for (int i = 0; i < theList.size(); i++) {
            System.out.printf(theList.get(i));
        }
    }
}
double-beep
  • 5,031
  • 17
  • 33
  • 41

2 Answers2

0

Call toString() for each element in printf, for example.

double-beep
  • 5,031
  • 17
  • 33
  • 41
Daniel Prosianikov
  • 100
  • 1
  • 1
  • 10
0

Use toString() method to retrieve a string represantation of the objects you want to print to the console. Read Java documentation about it here. In short here is what the method does:

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

theList.get(i).toString()

This answer will also give you a bit more information.

Another thing to mention is that you were trying to use printf method to log information about an object without providing the proper method arguments. Read more about printf here. Instead what you should be doing is using println method to print your information as mentioned above in new lines, as this method does not take any arguments:

System.out.println(theList.get(i).toString());
Matthew
  • 1,905
  • 3
  • 19
  • 26