0

I'm trying to create a class called ShipStorage which stores objects of submarine class in an array of type submarince class. When I use the getters and setters for the array submarine, it prints [LSubmarineClass;@27c170f0. Can someone please explain what is happening here and what I'm doing wrong?

class ShipStorage
{
    private Submarine[] submarine;

    public ShipStorage()
    {
        submarine = new Submarine[30];
        submarine[0] = new Submarine();

    }

    public void setSubmarine(Submarine[] inSubmarine)
    {
        submarine = inSubmarine;
    }

    public Submarine[] getSubmarine()
    {
        return submarine;
    }
}
public class Test
{
     public static void main(String[] args)
     {
     Submarine[] submarine = new Submarine[2];
     submarine[0] = new Submarine();
     submarine[1] = new Submarine(100.999, 1960, Submarine.TITAN, -242.53);

     ShipStorage store = new ShipStorage();
     store.setSubmarine(submarine);
     System.out.println(store.getSubmarine());
    }
}
Andronicus
  • 25,419
  • 17
  • 47
  • 88
yeri123
  • 21
  • 5
  • 1
    your getter returns what it should, but you can't print an array or a list like that, you have to print the individual elements. So: 1. override toString in your Submarine class 2. print the elements, not the array – Stultuske Mar 13 '20 at 13:23
  • This is how an array is printed. – Miss Chanandler Bong Mar 13 '20 at 13:23
  • @Stutsuke I already have a toString method in my class. So what I did now is that I created another array of type Submarine and stored the store.getSubmarine() into it and use a for loop to print out all the elements. Did I do it right? – yeri123 Mar 13 '20 at 13:41

1 Answers1

1

It does return an array, but to print it properly, you need to format the output:

System.out.println(Arrays.toString(store.getSubmarine()));
Andronicus
  • 25,419
  • 17
  • 47
  • 88