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("");
    }

Recommended Answers

All 3 Replies

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.

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("");
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.