As I was developing something, I wondered what might be the better/faster approach to create a bunch of objects while iterating over something.
Lets say we have this wrapper-class:
public class Photo{
private String url;
private String creator;
public Photo(String url, String creator){
this.url = url;
this.creator = creator;
}
// Getter methods down here...
}
And we have a JSONArray
of photos from which we want only the url
- and the creator
-strings:
JSONArray photos = json.getJSONArray("photos");
Photo[] photo_arr = new Photo[photos.length()];
// Iterate:
for (int i = 0; i < photos.length(); i++){
// Create the objects here.
}
Now, I see three possible solutions:
Creating temporary variables
Creating some temporary variables which get the desired values from the current object and then construct the new Photo
-object:
// Iterate:
String url = "";
String creator = "";
for (int i = 0; i < photos.length(); i++){
url = photos[i].getString("url");
creator = photos[i].getString("creator");
photo_arr[i] = new Photo(url, creator);
}
Use the returned-values directly in the constructor
Don't create temporary variables but use the returned values from the getString()
-method in the constructor-call:
// Iterate:
for (int i = 0; i < photos.length(); i++){
photo_arr[i] = new Photo(
photos[i].getString("url"),
photos[i].getString("creator")
);
}
Using setter-methods
Adding a no-parameter constructor and setter-methods for the url
and creator
to the wrapper-class and use them to populate the object:
// Iterate:
for (int i = 0; i < photos.length(); i++){
photo_arr[i] = new Photo();
photo_arr[i].setUrl( photos[i].getString("url") );
photo_arr[i].setCreator( photos[i].getString("creator") );
}
Which one is the better/faster/cleaner approach here?