ArrayList - use @override on the toString() method
An ArrayList of objects requires the output to be in the desired format, so it becomes necessary to modify the parent method of the Object class, not forgetting to specify that this class is inherited with the keyword @override.
We have two classes, Point and Main. The Point class has 2 attributes: x and y. As you can see, we used the keyword override In the method toString() in the main class. We also stored the instances of the point object in an ArrayList, and then we went through the ArrayList. You can see that the output takes the format defined in the method. toString(). You can program this method as needed.
We have two classes, Point and Main. The Point class has 2 attributes: x and y. As you can see, we used the keyword override In the method toString() in the main class. We also stored the instances of the point object in an ArrayList, and then we went through the ArrayList. You can see that the output takes the format defined in the method. toString(). You can program this method as needed.
public class Point {The main class:
private int x;
private int y;
public Point(int x, int y){
this.x=x;
this.y=y;
}
@Override
public String toString() {
return "[x= "+this.x+", y= "+this.y+"]";
}
}
import java.util.ArrayList;Run:
public class Main {
public static void main(String[] args) {
ArrayList< Item> list = new ArrayList< Item> ()
{
private static final long serialVersionUID = 1L;
@Override
public String toString()
{
return super.toString();
}
};
list.add(new Point(2, 4));
list.add(new Point(1, 6));
list.add(new Point(5, 2));
list.add(new Point(3, 7));
list.add(new Point(8, 9));
System.out.println(list.toString());
}
}
[[x= 2, y= 4], [x= 1, y= 6], [x= 5, y= 2], [x= 3, y= 7], [x= 8, y= 9]]In this example, ArrayList uses the method toString() declared in the Point class. If we remove the method toString() in the Point class, we will have the following format:
[Point@4a5f634c, Point@3c7038b9, Point@6b9c18ae, Point@55187eb3, Point@3b26456a]