2016-08-11 2 views
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); 
} 
+2

'varargs'를 사용할 수 있습니다. ,'Collection' 또는'Segment []'로 구성됩니다. 부가 적으로 당신이 여기서 정말로 묻고있는 것이 나에게 불투명하다. – SomeJavaGuy

+1

ArrayList 을 생성자에 전달하는 이유는 무엇입니까? –

답변

1

당신은 varargs이 사용할 수를 이것은 내가 지금까지 무엇을 가지고

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. 
+0

감사합니다. 이게 잘됐다. –

관련 문제