Ecl*_*pse -1 java arraylist tostring
我有一个class它有一个ArrayList在它与它的逻辑,我们称之为胃.
来自的两个实例class Meal和Drinks正在添加到ArrayList我的中的实例Main class.这两个类有一个覆盖方法返回getName()方法.
但是在我执行所有操作class的ArrayList地方,我不能使用foreach循环来使用对象的toString()方法ArrayList.
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);
}
Run Code Online (Sandbox Code Playgroud)
我尝试Stomach class在我拥有的地方创建一个属性ArrayList并从中调用方法,但我得到了一个NullPointerException因为名称尚不存在.
我必须以这种方式解决它,因为实现了返回名称的方法.
提前致谢.
覆盖和/或其子类中的toString方法,Digestion以返回为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;
}
}
Run Code Online (Sandbox Code Playgroud)
完整示例(实时复制):
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";
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
I'm a Meal instance I'm a Drink instance I'm a Snack instance
| 归档时间: |
|
| 查看次数: |
83 次 |
| 最近记录: |