Home > Software design >  How to print this object in Java?
How to print this object in Java?

Time:10-12

I'm new in java and yesterday my professor sent me a sample test. Unfortunately I got stuck in a task.

The task:

Write a class called MyArray which contains all necessary methods. After class instantiation, we would like to use this class in Main.java like this:

// comments : expected outputs

System.out.println(myarray1); // []
System.out.println(myarray1.size()); // 0
System.out.println(myarray1.isEmpty()); // true
myarray1.append(51);
myarray1.append(75);
myarray1.append(24);
System.out.println(myarray1); // [51, 75, 24]
System.out.println(myarray1.size()); // 3
int last = myarray1.getLast();
System.out.println(last); // 24
int first = myarray1.getFirst();
System.out.println(first); // 51
myarray1.appendAll(List.of(15, 95, 124));
System.out.println(myarray1); // [51, 75, 24, 15, 95, 124]
System.out.println(MyArray.InstCount); // 1 <instantiation counter>

I've successfully implemented all necessary methods, but I can't understand this line:

System.out.println(myarray1); // []

How can I print this object (ArrayList) directly?

I can't do that. My workaround is a new method called print(), and it print the myarray1 object:

In Main.java:

System.out.println(myarray1.print()); // []

In MyArray.java:

import java.util.List;
import java.util.ArrayList;

class MyArray
{
    public static int Count = 0;
    private List<Integer> numbers = new ArrayList<Integer>();

    MyArray()
    {
        Count  ;
    }

    public List<Integer> print()
    {
        return numbers;
    }

  .
  . // other methods...
  .

}

CodePudding user response:

print() is a bit of a weird name if that method doesn't actually print anything and instead constructs a string.

The println(Object obj) method exists in PrintStream (and System.out is a PrintStream). It prints objects by invoking their toString() method (which all Objects have - you can override it):

public class MyArr {
    @Override public String toString() {
       return whatever your print() method was returning.
    }
}

CodePudding user response:

It looks like you need to override the toString method. Something like this

class MyArray {

    // other fields

    @Override
    public String toString() {
        return numbers.toString();
    }
}
  • Related