-2

I just want to scan and display array using getter and setter method.It works fine in setter but when i am trying to call getter method instead of displaying array elements it display array class name. how can i display array elements using getter method??

    public class ArrayElements {

    private int[] arrayElements;

    public int[] getArrayElements() {
        return this.arrayElements;
    }

    public void setArrayElements(int[] arrayElements) {
        this.arrayElements = arrayElements;
    }
}
public class BubbleSort {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        ArrayElements arrayElements = new ArrayElements();
        int[] element = new int[5];
        System.out.println("Enter Elements :");
        for (int i = 0; i < element.length; i++) {
            element[i] = scanner.nextInt();
        }
        arrayElements.setArrayElements(element);
        System.out.println(arrayElements.getArrayElements());
    }

}
Enter Elements :
10 20 0 45 56

[I@299a06ac
Kapil
  • 817
  • 2
  • 13
  • 25

3 Answers3

1

Try something like this:

System.out.println(Arrays.toString(arrayElements.getArrayElements()));

Other solutions you can find here

lczapski
  • 4,026
  • 3
  • 16
  • 32
1

To display the elements of your array you should use

System.out.println(Arrays.toString(arrayElements.getArrayElements()));

Your call just shows the memory address of your int array.

MaS
  • 393
  • 3
  • 17
1

Addition to other answers, explaining why do you get strange on first sight results.

Everytime you call System.out.println(object) and pass some object there, internally a toString() method is called within println(). So the call is equal to System.out.println(object.toString()). It's done for getting valid string representation of the object you're trying to print.

An array is a reference type, and it's of type Object. You don't override toString() method for array, so its default implementation falls down to Object class. Implementation of Object class toString() method:

public String toString()
{
      return getClass().getName()+"@"+Integer.toHexString(hashCode());
}

As you can see here this method prints out name of class, symbol "@" and hashcode in hex format.

See reference here: https://www.geeksforgeeks.org/object-tostring-method-in-java/enter link description here

Dmitriy Fialkovskiy
  • 3,065
  • 8
  • 32
  • 47
  • thank you for giving me good explanation about the problem :). i tried Arrays.toString and it worked – Harsh Pithadia Aug 16 '19 at 05:53
  • @HarshPithadia, consider accepting answer if you think it was useful for you=) Maybe not even my answer, other peoples` answers are valid too and closer to your initial question. – Dmitriy Fialkovskiy Aug 16 '19 at 06:07