WB Lee
WB Lee

Reputation: 841

how to make these two java generic method declared in the same class

I want to declare two methods. One of them should print List, and another one should print List>. So I declared the following codes, but there is something wrong with them. Is there anyone could help me to solve this problem.

/* print the List<List<String>> */
public static <T> void print(List<List<T>> set) {
    if (set == null) return;
    for (List<T> subSet : set) {
        System.out.print("[");
        for (int i = 0; i < subSet.size() - 1; i++) {
            System.out.print(subSet.get(i) + ", ");
        }
        if (subSet.size() >= 1) {
            System.out.print(subSet.get(subSet.size() - 1));
        }
        System.out.println("]");
    }
}

 /* print the List<String> */
public static <T> void print(List<T> set) {
    if (set == null) return;
    int size = set.size();
    System.out.print("[");
    for (int i = 0; i < size - 1; i++) {
        System.out.print(set.get(i) + ", ");
    }
    System.out.println(set.get(set.size() - 1) + "]");
}

Upvotes: 1

Views: 75

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533442

There is a risk that the second method is called when it is actually the first type if the compiler doesn't know the type has a nested list.

I would combine them

public static <T> void print(Collection<T> set) {
    if (set == null) {
       System.out.print("null");
       return;
    }
    System.out.print("[ ");
    String sep = "";
    for (T t : set) {
        System.out.print(sep);
        sep = ", ";
        if (t instanceof Collection) {
            print((Collection) t);
        } else {
            System.out.print(t);
        }
    }
    System.out.print(" ]");
}

public static <T> void println(Collection<T> set) {
    print(set);
    System.out.println();
}

Upvotes: 1

Related Questions