[英]Java Printing ArrayList of ArrayList
I am trying to print my arraylist but i don't know why my printing does not print line by line of IntegerPair in each index of Adjlist: 我正在尝试打印我的arraylist,但是我不知道为什么我的打印不能在Adjlist的每个索引中逐行打印IntegerPair:
private ArrayList<ArrayList<IntegerPair>> AdjList; //outer arraylist
private ArrayList<IntegerPair> storeNeighbour; //inner arraylist
private IntegerPair pair;
This is my snippet: 这是我的片段:
for (ArrayList<IntegerPair> l1 : AdjList) {
for (IntegerPair n : l1) {
System.out.println( n + "# ");
}
}
The default behavior of ArrayList.toString() is to return a single string containing a (somewhat) beautified list of calls to toString()
on each element in the list. ArrayList.toString()的默认行为是返回一个字符串,该字符串包含列表中每个元素上
toString()
的(某种程度上)美化的调用列表。
So, long story short: you are almost there; 所以,长话短说:你快到了; the one thing that is missing:
缺少的一件事:
@Override
public String toString() {
...
within your class IntegerPair. 在您的IntegerPair类中。
Like: 喜欢:
public class IntegerPair {
private final Integer first;
private final Integer second;
...
@Override
public String toString() {
return "(" + first + "/" + second ")";
}
or something alike. 或类似的东西。 Without overriding
toString()
your class will fall back on the default implementation given in java.lang.Object; 在不重写
toString()
的情况下,您的类将依赖于java.lang.Object中提供的默认实现; and that method returns class name + hashcode number (and is thus not so human-readable). 并且该方法返回类名+哈希码号(因此不是人类可读的)。
Here : 这里 :
for (ArrayList<IntegerPair> l1 : AdjList) {
for (IntegerPair n : l1) {
System.out.println( n + "# ");
}
}
You don't differentiate each printed List. 您无需区分每个打印的列表。
As a result, you will have a series of output without knowing those associated to a same list. 结果,您将获得一系列输出,而无需知道与同一列表相关联的输出。
A more readable print would be : 更具可读性的印刷品为:
for (ArrayList<IntegerPair> l1 : AdjList) {
System.out.println("ArrayList with :");
for (IntegerPair n : l1) {
System.out.println( n + "# ");
}
}
You don't specify your output. 您没有指定输出。 So I don't suppose
toString()
is or not overridden. 所以我不认为
toString()
是否被重写。 If it is not overridden you should either override it to render the String expected here : System.out.println( n + "# ");
如果未重写它,则应该重写它以呈现此处期望的String:
System.out.println( n + "# ");
, or you should specify the content to render here : ,或者您应在此处指定要呈现的内容:
System.out.println( n.getOne() + "," + n.getOther() + "# ");
As a side note, toString()
is designed for debugging/logging, not for displaying functional messages as an object could be rendered in a way for a case and in another way for other cases. 附带说明一下,
toString()
设计用于调试/记录日志,而不用于显示功能消息,因为可以以一种情况呈现对象,而以其他方式呈现对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.