Java. Call a method that returns an array and display it without displaying the memory address

0

My question is, how can I show from my main, a method that is returning an array without returning a memory address ?. My code is now like this.

Main

System.out.println(ciudad1.getMaximas());
//Aqui quiero que me imprima lo que contiene el array, pero sale la direccion de memoria.

Clase
float []getMaximas(){
return temperaturaMaxima;     
}
    
asked by 28.01.2017 в 16:45
source

5 answers

5

Arrays are objects that inherit the implementation of toString() of Object (which is that rare string with numbers - not necessarily a memory location -).

You can not reimplement the toString() method of an array, so there are two options:

  • Iterate over the array (for example with enhanced for ) and print each item in the array separately.

  • Use the toString(Object[]) method of java.util.Arrays , which does more or less the same.

answered by 28.01.2017 в 17:30
2

Hello, you can do it by importing the Class java.util.Arrays;

and replacing your code:

System.out.println (city1.getMaximums ());

for the following

System.out.println (Arrays.asList (city1.getMaximums ()));

I hope you serve

Greetings.

    
answered by 06.02.2017 в 16:13
1

An array is an object, and what you are shown is not a memory address, but simply a name assigned to the object. What you have to do is iterate over the arrangement to show it:

float[] temperaturaMaxima = { 22.488L, 32.433L, 27.32L  };

public float[] getMaxima(){
    return temparaturaMaxima;
}

public String arregloToJSONString(float[] arreglo){
    StringBuilder sb = new StringBuilder();
    sb.append("[ ");
    for (int i = 0; i<arreglo.length; i++ ){
        sb.append(String.valueOf(arreglo[i]));
        if (i<arreglo.length-1) sb.append(", ");
    }
    sb.append(" ]");
    return sb.toString();
}

The code gives you a representation of the arrangement in this case in JSON format, but in the background you choose how to present your data.

System.out.println(arregloToJSONString(getMaxima()));
// => "[ 22.488, 32.433, 27.32 ]
    
answered by 28.01.2017 в 19:16
1

A loop? How about ...

System.out.println("Array:");
for(Float numero: ciudad1.getMaximas())
    System.out.println("-- "+numero);
    
answered by 28.01.2017 в 23:24
-1

Use a toString method. I think java arrays by default have one defined. If not, you can overwrite the method itself to return a string with the format you want.

    
answered by 28.01.2017 в 17:21