khalildz34
khalildz34

Reputation: 25

Creating n Object of array in java

I am having issues understanding how to create an array of n objects in Java.

This is the constructor of class ServicePath as follows:

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

This is the elements of the array that I would like to create the objects.

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

I tried the following, but it creates it manually.

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

For example, manually it creates the following

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

I would like to create it automatically using String ServicePathArrays in such way:

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

Upvotes: 0

Views: 85

Answers (2)

Mustapha Belmokhtar
Mustapha Belmokhtar

Reputation: 1219

This could be done using the functional behavior of 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); 

Upvotes: 1

Nagendra Varma
Nagendra Varma

Reputation: 2315

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

Upvotes: 1

Related Questions