[英]Adding multiplie objects to an ArrayList in java
我有一個名為Customer
的類,它存儲以下對象:
private String CustomerFirstName
private String CustomerLastName
private String CustomerID
private String CustomerEmail
現在,為了將數據傳遞給jasper報告,我決定創建一個包含這些對象的數組列表,因此:
import java.util.ArrayList;
import java.util.Collection;
/* This is CustomerDataSource.java file */
public class CustomerDataSource {
public static Collection<Customer> loadCustomers() throws Exception {
Collection<Customer> customers = new ArrayList<Customer>();
Customer customer = new customer (
/* I need help getting the objects CustomerFirstName / CustomerLastName and etc */
);
customer.addBilling(new Billing ( /* Adding billing info */ ));
customer.getBilling(new Billing ( /* I need to get the object's values*/));
customer.balOwing();
customers.add (customer);
return customers;
}
}
有人可以解釋如何將Customer.java
的對象添加到數組列表嗎? (通常,因為我也需要添加來自不同文件的對象。謝謝
因此,正如我在評論中看到的問題一樣,您想創建一個構造函數。
在您的Costumer課程中
public Costumer(String firstName, String lastName, String ID, String email) {
this.CostumerFirstName = firstName;
this.CostumerLastName = lastName;
this.CostumerID = ID;
this.CostumerEmail = email;
}
因此,您可以像這樣創建一個新的客戶:
Customer customer = new Customer ("SampleFirstName","SampleLastName","0000","address@web.com");
您甚至可以通過將其添加到構造函數中,將客戶自動添加到ArrayList中。
根據您的評論,我猜您想使用構造函數嗎?
您將必須在Customer.java
上添加一個構造函數。
public Customer(String firstName, String lastName, String id, String email){
this.CustomerFirstName = firstName;
this.CustomerLastName = lastName;
this.CustomerID = id;
this.CustomerEmail = email;
}
您可能需要使用getter / setter方法來訪問上述變量。
ArrayList<E>.get(i)
在靜態數組中實際上執行與[]
完全相同的功能。 兩者之間的唯一區別是ArrayList<E>.get(i)
僅適用於對象上下文。 換句話說,您可以取消引用它。
首先,您需要將Customer
字段的隱私更改為public,以授予ArrayList<Customers>
對象訪問權限。 然后,您可以使用以下簡單方法檢索您的班級字段:
customers.get(index).FirstName //or whatever other field
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.