【问题标题】:Regarding toString() and memory reference in an ArrayList关于 ArrayList 中的 toString() 和内存引用
【发布时间】:2016-07-09 12:37:30
【问题描述】:

我有一个class,其中有一个ArrayList,它的逻辑让我们称之为胃。

还有来自classMealDrinks 的两个实例被添加到我的ArrayList 中的ArrayList class。这两个类有一个被覆盖的 Method,它返回 getName() 方法。

但是在我执行所有操作的ArrayListclass 中,我不能使用foreach 循环使用ArrayList 对象的toString() 方法。

public void amountOfElements() {
    for (Digestion d : stomach) {
        //prints the hash code. I can't call the corresponding toString() equivalent in here.
         System.out.println(d);
    }

我尝试在Stomach class 中创建一个属性,其中我有ArrayList 并从中调用方法,但我得到了一个NullPointerException,因为该名称还不存在。

我必须这样解决,因为返回名字的方法实现了。

提前致谢。

【问题讨论】:

  • “打印内存位置” 不,它没有。它打印来自Object#toString 的默认输出,其中包括哈希码,而不是内存位置。
  • 请澄清并扩展您的问题,包括显示更多相关代码,以便我们充分理解问题。
  • 一方面,您没有向我们展示引发 NullPointerException 的行,这是帮助我们找到确切错误的关键信息>.

标签: java arraylist tostring


【解决方案1】:

覆盖Digestion 和/或其子类中的toString 方法,以返回您希望为Digestion 实例输出的任何字符串:

class Digestion { // or `class Meal` or `class Drink` or `class Stomach`, etc.
    // ...other implementation...

    @Override
    public String toString() {
        String result;
        /* logic assigning to `result` goes here */
        return result;
    }
}

完整示例 (live copy):

class Example
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Digestion[] stomach = new Digestion[] {
            new Meal(),
            new Drink(),
            new Snack()
        };

        for (Digestion d : stomach) {
            System.out.println(d);
        }
    }
}
class Digestion {
    @Override
    public String toString() {
        return "I'm a Digestion instance";
    }
}
class Meal extends Digestion {
    @Override
    public String toString() {
        return "I'm a Meal instance";
    }
}
class Drink extends Digestion {
    @Override
    public String toString() {
        return "I'm a Drink instance";
    }
}
class Snack extends Digestion {
    @Override
    public String toString() {
        return "I'm a Snack instance";
    }
}

输出:

我是 Meal 实例 我是一个 Drink 实例 我是 Snack 实例

【讨论】:

  • 谢谢,@蒂姆。我刚刚意识到同样的事情,当我发现你已经有了时,我打算修复。
  • 我不需要 Digestion 实例,而是 Meal and Drink 实例。在 ArrayList 中作为 toString() 输出。
  • @Eclipse:好吧,只需将原理应用到您需要应用它的地方。请记住,实际对象的toString 将被调用。
【解决方案2】:

为了能够做到这一点:

for (Digestion d : stomach) {

stomach 必须持有 Digestion 对象或实现 Digestions 的对象,具体取决于 Digestion 是什么(类或接口)

因此您需要确保 MealDrinks 是 Super 类 Digestion 的子类,并且它们都具有 @987654322 @方法被正确覆盖...

所以 每个类都应该有一个类似的方法

@Override
public String toString() {
    return //here you have to define what better describe the Meal or Drink;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 2013-08-23
    • 2015-06-10
    • 2015-11-01
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多