英文:
How should the toString() methods in ClassA and ClassB be written to take advantage of the natural toString() method in ClassB?
问题
import java.util.ArrayList;
public class ClassA {
ArrayList<ClassB> list = new ArrayList<ClassB>();
String numberList = "";
public String toString() {
for (ClassB object : list)
numberList += object + " ";
return numberList;
}
public static void main(String args[]) {
ClassA y = new ClassA();
int[] v = {4, 3, 7, 5, 99, 3};
for (int m : v)
y.list.add(new ClassB(m));
System.out.println(y);
}
}
class ClassB {
int x;
ClassB(int a) {
x = a;
}
public String toString() {
return String.valueOf(x);
}
}
英文:
import java.util.ArrayList;
public class ClassA {
ArrayList<ClassB> list = new ArrayList<ClassB>();
public static void main(String args[]) {
ClassA y = new ClassA();
int[] v = { 4, 3, 7, 5, 99, 3 };
for (int m : v)
y.list.add(new ClassB(m));
System.out.println(y);
} // end main
} // end class ClassA
class ClassB {
int x;
ClassB(int a) {
x = a;
}
} // end ClassB
How should the methods in ClassA and ClassB be written to give the indicated output and take advantage of the natural toString method in ClassB? (Assuming this should be ClassA?)
The output should be as follows: 4 3 7 5 99 3
For class A, I made the following changes.
import java.util.ArrayList;
public class ClassA {
ArrayList<ClassB> list = new ArrayList<ClassB>();
String numberList = "";
public String toString() {
for (ClassB object : list)
numberList += object + " ";
return numberList;
}
public static void main(String args[]) {
ClassA y = new ClassA();
int[] v = {4, 3, 7, 5, 99, 3 };
for (int m : v)
y.list.add(new ClassB(m));
System.out.println(y);
} // end main
} // end class ClassA
For class B
class ClassB {
int x;
ClassB(int a) {
x = a;
}
public String toString() {
return String.valueOf(x);
}
} // end ClassB
I probably did this wrong, but does anyone have better insight on this?
答案1
得分: 2
一旦你在 H2ClassB 中编写了一个 .toString()
方法,那么 H2ClassA 的 main
方法中的 println
将会正确显示。
指令:System.out.println(y);
将尝试显示一个 ArrayList,该 ArrayList 具有自己的 toString
方法,输出将会像是 [stuff, stuff, stuff, stuff],但 'stuff' 将是你的列表元素的 toString
结果,这些元素是 H2ClassB 对象。如果没有自定义的 toString
方法,你会看到它们被替代为二进制引用。
英文:
Once you write a .toString()
method in H2ClassB, then the println in H2ClassA's main method would display properly.
The instruction: System.out.println (y);
will attempt to display an ArrayList, which has its own toString
method, and the output would look like [stuff, stuff, stuff, stuff] , but 'stuff' will be the result of a toString of your elements of your list, which are H2ClassB objects. Without a custom toString
you are seeing binary references in its place.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论