How to print a nested ArrayList?

56 Views Asked by At

I want to print a nested ArrayList in Java as the title suggests and I'm unable to do that because of conflict with another method.

Here's my code:

import java.util.*;
class TBF
{
    <T> void print(ArrayList<T> a)
    {
        for(int i=0;i<a.size();i++)
        System.out.print(a.get(i)+" ");
        System.out.println();
    }

    <T> void print(ArrayList<ArrayList<T>> a) // this line shows the error: "Erasure of method print(ArrayList<ArrayList<T>>) is the same as another method in type TBF"
    {
        for(int i=0;i<a.size();i++)
        print(a.get(i));
    }

    public static void main(String args[])
    {
        // some code
    }
}

This is unlike any error I received while writing the equivalent code in C++ with vector.

So I then tried this:

import java.util.*;
class TBF
{
    <T> void print(ArrayList<T> a)
    {
        for(int i=0;i<a.size();i++)
        if(a.get(i) instanceof Integer || a.get(i) instanceof Long || a.get(i) instanceof String)
        System.out.print(a.get(i)+" ");
        else
        print(a.get(i)); // this time the error is: "The method print(ArrayList<T>) in the type TBF is not applicable for the arguments (T)"
        System.out.println();
    }

    public static void main(String args[])
    {
        // some code
    }
}

Now I can't understand how I'm supposed to print a 2D ArrayList. Please help.

1

There are 1 best solutions below

1
Yahor Barkouski On

This is a classic case of Java's type erasure (https://www.baeldung.com/java-type-erasure), a concept where Java kind of forgets about the specific type of your lists at compile-time, causing both print methods to look identical to it.

What you can do is to check the type of list elements on-the-go: If you find a list inside your list, just call the print method again, for that inner list. If you find a non-list item, just print it, kinda:

class TBF {
    void print(List<?> list) {
        for (Object o : list) {
            if (o instanceof List<?>) {
                print((List<?>) o);
            } else {
                System.out.print(o + " ");
            }
        }
        System.out.println();
    }

    public static void main(String args[]) {
        // some code
    }
}