Question

How can I call the array function in Java?

Currently it looks like:

public static void WriteLine(Object Array[]) {
    for (int I = 0; I < Array.length; ++I) {
        Out.println(Array[I]);
    }
}

public static void WriteLine(Object Text) {
    Out.println(Text);
}

I also tried:

public static <T> void WriteLine(T Array[]) {
    for (int I = 0; I < Array.length; ++I) {
        Out.println(Array[I]);
    }
}

and in my main, I do:

int[] I = new int[]{1, 2, 3, 4, 5};
WriteLine(I);

I also tried:

WriteLine<int[]>(I);

Doesn't work..

It prints: [I@2f56f920

aka the address of the int Array. How can I call the specific array function explicitly or how can I make the compiler know which one to call automatically (implicitly)?

I'm not used to Java/Generics/Object yet.. Just moved from C++ and used to templates :(

Was it helpful?

Solution

An int is not an Object so an int[] is not an Object[]:

Integer[] I = new Integer[]{1, 2, 3, 4, 5};
WriteLine(I);

Or you should have WriteLine overloaded for all the primitive types:

public static void WriteLine(int Array[]) {
...
public static void WriteLine(long Array[]) {
...

OTHER TIPS

I would go for

System.out.println(Arrays.toString(myArray));

I would name your array something other than "Array," as Java is confusing the Array class with the Object or T generic class. You may want to also consider using StringBuilder, if all you want is to print each element of your array.

public static void write(Object arr[]) {
    for (int i = 0; i < arr.length; ++i) {
        System.out.println(arr[i]);
    }
}

Should be good enough.

If you really want to use StringBuilder, and then print, do this:

public static void write(Object arr[]) {
    sb = new StringBuilder();
    for (int i = 0; i < arr.length; ++i) {
        sb.append(arr[i] + " ");
    }
    System.out.println(sb.toString());
}

array of primitive are subtype of java.lang.Object. Overloading is resolved at compile time and the most specific method is selected which in case is writeLine(Object text).

You have two options to make sure that the right function is called:

1-

Object[] objArray = new Object[] { 1, 2, 3, 4, 5 };

2-

Integer[] integerArray = new Integer[] { 1, 2, 3, 4, 5 };

On a side note, you should follow Java naming conventions. for example method name should be writeLine and the index variable in the loop should be small case

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top