简体   繁体   English

如何在Java中打印这个object?

[英]How to print this object in Java?

I'm new in java and yesterday my professor sent me a sample test.我是 java 的新人,昨天我的教授给我发了一份样本测试。 Unfortunately I got stuck in a task.不幸的是我被困在一个任务中。

The task:任务:

Write a class called MyArray which contains all necessary methods.编写一个名为MyArray的 class,其中包含所有必要的方法。 After class instantiation, we would like to use this class in Main.java like this:在 class 实例化之后,我们想在 Main.java 中使用这个 class,如下所示:

// 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?如何直接打印这个 object (ArrayList)?

I can't do that.我不能那样做。 My workaround is a new method called print() , and it print the myarray1 object:我的解决方法是使用一种名为print()的新方法,它会打印 myarray1 object:

In Main.java:在 Main.java 中:

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

In MyArray.java:在 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...
  .

}

print() is a bit of a weird name if that method doesn't actually print anything and instead constructs a string.如果该方法实际上不打印任何内容而是构造一个字符串,那么print()这个名字有点奇怪。

The println(Object obj) method exists in PrintStream (and System.out is a PrintStream). PrintStream中存在println(Object obj)方法(而System.out是一个 PrintStream)。 It prints objects by invoking their toString() method (which all Objects have - you can override it):它通过调用它们的toString()方法来打印对象(所有对象都有 - 你可以覆盖它):

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

It looks like you need to override the toString method.看起来您需要重写toString方法。 Something like this像这样的东西

class MyArray {

    // other fields

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM