Reputation: 45
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:
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 + "# ");
}
}
Upvotes: 0
Views: 534
Reputation: 131526
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. If it is not overridden you should either override it to render the String expected here : 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.
Upvotes: 0
Reputation: 140613
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.
So, long story short: you are almost there; the one thing that is missing:
@Override
public String toString() {
...
within your class 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; and that method returns class name + hashcode number (and is thus not so human-readable).
Upvotes: 4