簡體   English   中英

使用臨時對象從數組創建ArrayList

[英]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);
    }
  • 無需先添加此人以便以后替換它
  • 無需使引用無效 - 列表將在任何情況下保留對temp對象的引用。
  • 而不是直接設置值,您可以使用setter( setName()而不是.name =
  • 如果您使用setter,則可以實現Builder模式:

像這樣:

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM