2017-12-20 2 views
0

Ich habe Probleme zu verstehen, wie ein Array von n Objekte in Java erstellen. Erstellen n Objekt des Arrays in Java

Dies ist der Konstruktor der Klasse ServicePath wie folgt:

public ServicePath(String id) { 
    this.id = id; 
} 

Diese Elemente des Arrays ist die Ich mag würde die Objekte erstellen.

String ServicePathArrays[] = {"SH11","SH13","SH17","SH110","SH111","SH112","SH115", ...} 

Ich habe Folgendes versucht, aber es erstellt es manuell.

ServicePath[] servicePathArray = new ServicePath[ServicePathArrays.length]; 

Zum Beispiel manuell erstellt es die folgenden

ServicePath[0] = new ServicePath("SH11"); 
ServicePath[1] = new ServicePath("SH13"); 
.. 
.. 

Ich mag würde es automatisch String ServicePathArrays in einer solchen Art und Weise mit erstellen:

ServicePath[0].id = "SH11"; 
ServicePath[1].id = "SH12"; 
ServicePath[2].id = "SH13"; 
.. 
.. 
+0

Sind Sie auf der Suche nach dem * kompaktesten Weg? – kryger

Antwort

1

Dies getan werden könnte, Verwenden des Funktionsverhaltens von jdk8 +:

String servicePathArray[] = {"SH11", "SH13", "SH17", 
          "SH110", "SH111", "SH112", "SH115"}; 
List<ServicePath> collection = Stream.of(servicePathArray) 
            .map(ServicePath::new) 
            .collect(Collectors.toList()); 

System.out.println(collection); 
+1

Es ist prägnanter, 'Stream.of (servicePathArray)' als 'Arrays.asList (servicePathArray) .stream()' zu haben. Und noch prägnanter ist "Stream.of" ("SH11", "SH13", ..., "SH115"). – DodgyCodeException

+0

Ich stimme zu: +1 für diesen Hinweis –

1
String ServicePathArrays[] = {"SH11","SH13","SH17","SH110","SH111","SH112","SH115", ...}; 
ServicePath[] servicePathArray = new ServicePath[ServicePathArrays.length]; 
for(int i = 0; i < ServicePathArrays.length; i++) { 
    servicePathArray [i] = new ServicePath(ServicePathArrays[i]); 
} 
Verwandte Themen