[SOLVED] how do i create a Method that accepts both String[] and Integer[] in java without method overloading?


Let’s say you have an integer array and a string array. How can you write a SINGLE method printArray that can print all the elements of both arrays. The method should be able to accept both integer arrays or string arrays. NOTE.. I cannot use method overloading. Any idea to how to go about this?


The only way I see is

public void print(Object o) {
    if (o instanceof String[]) {
        System.out.println(Arrays.toString((String[]) o));
    else if (o instanceof int[]) {
        System.out.println(Arrays.toString((int[]) o));

But it’s absolutely ugly. You should have two different methods.

If what you have is an Integer[] (instead of an int[]), then it’s simpler, and OK:

public void print(Object[] o) {

Answered By – JB Nizet

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *