Steingrim Steingrim - 1 year ago 74
Java Question

Inialize object with 0 to multiple objects from another class java

I have a Path and a Segment class. A path consists of multiple segments, and the number of segments can vary. When a new Path is initialized I want to be able to add 0 or multiple segments in the path object. This is what I have so far:

public class Segment {

private final double distance;
private final double duration;

public Segment(double distance, double duration){
this.distance = distance;
this.duration = duration;

public class Path {

public ArrayList<Segment> segments;
private Segment segment;

public Path(Segment segment){
// parameter should be able to take in 0-multiple segment-objects
this.segment = segment;
this.segments = new ArrayList<Segment>();

Main method example:

public static void main(String[] args){
Path path1 = new Path(segment1, segment2, segment3);
Path path2 = new Path(segment4);

Answer Source

You could use varargs:

import java.util.Arrays;
import java.util.List;

public class Path {
    private final List<Segment> segments;

    public Path(Segment... segs) {
        this.segments = Arrays.asList(segs);

Then you can call it supplying zero or more segments:

Segment seg1 = new Segment(2.0, 3.5);
Segment seg2 = new Segment(1.4, 4.2);

Path example1 = new Path();            // no segments
Path example2 = new Path(seg1);
Path example3 = new Path(seg1, seg2);  // etc.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download