Inialize对象为0,来自另一个类java的多个对象

时间:2016-08-11 11:11:06

标签: java oop aggregation

我有一个Path和一个Segment类。路径由多个段组成,段的数量可以变化。初始化新路径时,我希望能够在路径对象中添加0或多个段。这就是我到目前为止所做的:

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>();
  }
}

主要方法示例:

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

1 个答案:

答案 0 :(得分:1)

您可以使用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);
    }
}

然后你可以调用它来提供零个或多个段:

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.