Reputation: 63
I know there are standard way by add a constructors to the class. But for classes with object superclass (has no-argument constructor) I tend to find using a temporary object simpler. Is there any down side for such an act.
import java.util.ArrayList;
public class Main {
public static void main(String[] args){
// data available in two separated arrays
String[] dName = {"Sam","Ben","Joye","Sarah","Tim","Lucy","Jack"} ;
int[] dAge= {10,52,53,15,12,60,21};
// Array list to put the data in
ArrayList<Person> personList =new ArrayList<Person>(7);
for (int i=0;i<dName.length;i++){
Person tempPerson = new Person();
tempPerson.name= dName[i];
tempPerson.age= dAge[i];
personList.add(new Person());
personList.set(i,tempPerson);
tempPerson=null; //removes the reference
}
for (int j=0 ; j<personList.size();j++){
System.out.println(personList.get(j).name+" age is "+personList.get(j).age );
}
}
}
class Person{
String name;
int age;
}
the output
Sam age is 10
Ben age is 52
Joye age is 53
Sarah age is 15
Tim age is 12
Lucy age is 60
Jack age is 21
Upvotes: 2
Views: 1377
Reputation: 515
You should use a constructor for Person. Then you have just one call in your for-loop:
personList.add(new Person(dName[i], dAge[i])
Also, in your implementation, you are doing the necessary work twice, because you call personList.add(new Person())
and then you call personList.set(i, temPerson)
. If you don't want a constructor in your Person-class, a call of personList.add(tempPerson)
for example would be enough.
Upvotes: 3
Reputation: 13858
You should avoid statements that do nothing - an optimization would be to do
for (int i=0;i<dName.length;i++){
Person tempPerson = new Person();
tempPerson.name= dName[i];
tempPerson.age= dAge[i];
personList.add(tempPerson);
}
setName()
instead of .name =
)like this:
public Person setName(String aName) {
name = aName;
return this;
}
Resulting in something like
personList.add(new Person().setName(dName[i]).setAge(dAge[i]));
Then again - the two value constructor will probably be the easiest of all - and it don't matter that the super class doesn't have a constructor:
public Person(String aName, int aAge) {
name = aName;
age = aAge;
}
//You can have more than one constructor
public Person() {
}
and then
personList.add(new Person(dName[i], sAge[i]));
Upvotes: 4
Reputation: 1288
Not really,
you could maybe make use of java8 streams, but why make your life harder, it wouldnt add anything new
Upvotes: 0