1
Path 및 Segment 클래스가 있습니다. 경로는 여러 세그먼트로 구성되며 세그먼트 수는 다를 수 있습니다. 새 Path를 초기화 할 때 경로 객체에 0 또는 여러 세그먼트를 추가 할 수 있기를 원합니다.다른 클래스의 여러 객체에 0으로 객체 초기화 java
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>();
}
}
주요 메소드 예 :
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);
}
}
그런 다음 당신이 0 개 이상의 세그먼트를 공급 호출 할 수 있습니다 :
public static void main(String[] args){
Path path1 = new Path(segment1, segment2, segment3);
Path path2 = new Path(segment4);
}
'varargs'를 사용할 수 있습니다. ,'Collection' 또는'Segment []'로 구성됩니다. 부가 적으로 당신이 여기서 정말로 묻고있는 것이 나에게 불투명하다. – SomeJavaGuy
ArrayList을 생성자에 전달하는 이유는 무엇입니까? –