I am working on condensing my code for a project. Is there a way to print multiple primative types of arrays with the same method? I know you can with using "Object" but these are primative. Should I change them to Integer, Double, Boolean, etc and do it that way?

public void printArray(int []a){
        for(int i = 0;i<a.length;i++)
            System.out.print(a[i] + " ");
        System.out.println("");
    }

    public void printArray2(boolean []a){
        for(int i = 0;i<a.length;i++)
            System.out.print(a[i] + " ");
        System.out.println("");
    }

    public void printArray3(double []a){
        for(int i = 0;i<a.length;i++)
            System.out.print(a[i] + " ");
        System.out.println("");
    }

The OP's code does not use objects. Its only primitives.
Why not overload the method vs having a new name for every type.

See the Arrays class's toString() method.

Edited 4 Years Ago by NormR1

NormR1 is right. I totally forgotten about method overloading. However, he mention just 1 method and I assume he meant creating only 1 method that does the print array without creating 3 methods? Not quite sure what he wants so will have to wait for him to reply.

The code below should work too.

public void printArray(int []a){
    for(int i = 0;i<a.length;i++)
        System.out.print(a[i] + " ");
    System.out.println("");
}
public void printArray(boolean []a){
    for(int i = 0;i<a.length;i++)
        System.out.print(a[i] + " ");
    System.out.println("");
}
public void printArray(double []a){
    for(int i = 0;i<a.length;i++)
        System.out.print(a[i] + " ");
    System.out.println("");
}
This article has been dead for over six months. Start a new discussion instead.