![](/img/trans.png)
[英]Create a new object from user input using array and not ArrayList in Java
[英]Create ArrayList from array using temporary object
我知道通過在類中添加構造函數有標准方法。 但對於具有對象超類(具有無參數構造函數)的類,我傾向於發現使用更簡單的臨時對象。 這種行為是否有任何不利因素。
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;
}
輸出
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
你應該避免不做任何事情的陳述 - 優化就是要做
for (int i=0;i<dName.length;i++){
Person tempPerson = new Person();
tempPerson.name= dName[i];
tempPerson.age= dAge[i];
personList.add(tempPerson);
}
setName()
而不是.name =
) 像這樣:
public Person setName(String aName) {
name = aName;
return this;
}
導致像
personList.add(new Person().setName(dName[i]).setAge(dAge[i]));
然后再次 - 兩個值構造函數可能是最簡單的 - 並且超類沒有構造函數並不重要:
public Person(String aName, int aAge) {
name = aName;
age = aAge;
}
//You can have more than one constructor
public Person() {
}
接着
personList.add(new Person(dName[i], sAge[i]));
您應該為Person使用構造函數。 然后你的for循環中只有一個調用:
personList.add(new Person(dName[i], dAge[i])
此外,在您的實現中,您正在進行兩次必要的工作,因為您調用personList.add(new Person())
然后調用personList.set(i, temPerson)
。 如果你不想在你的Person類中使用構造函數,那么調用personList.add(tempPerson)
就足夠了。
並不是的,
你可以使用java8流,但為什么讓你的生活更難,它不會添加任何新東西
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.