1

I have something like the following:

List<Interval> intervals = new LinkedList<Interval>();
intervals.add(new Interval(1));
intervals.add(new Interval(2));

How can I print the List intervals? I attempted System.out.println(intervals), but it simply returns [Interval@...].

Thank you

2 Answers2

0

The issue is not in printing the List but in printing the Interval.

Implement Interval.toString() method.

Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43
0

System.out.println(intervals) will call .toString() method of the object you are trying to print, which is List.

In order to print every object you have to override the toString() method for Interval or print specific value.

for (Inteval interval : intervals) { System.out.println(interval.getValue());}

or if you override the toString() method for Interval

for (Inteval interval : intervals) { System.out.println(interval);}

You can override the toString() as follows:

public class Interval {
    public int value;
    public String val; 

    @Override
    public String toString() {
        return "Value string: " + val + " value int: " + value;
    }
}
Turbut Alin
  • 2,568
  • 1
  • 21
  • 30