[英]How can I access elements within a list of Objects
我正在定義一個 ArrayList
ArrayList <Object> p = new ArrayList<Object>();
現在到ArrayList
我像這樣添加
String source = "hi";
int x,y,year = 0;
p.add(new Object(source,x,y,year));
p.add(new Object(source+"hello",x+1,y+1,year+1));
現在在 main 方法中,我想訪問對象列表中的特定元素。 我該怎么做?
當我在 main 方法中打印出來時,它輸出
[source,x,y,year, source1,x1,y1,year1]
但是,我只想要第一個元素的來源。 所以只輸出“hi”作為字符串類型而不是對象。
實現所需結果的一種方法是使用Arrays.asList()
將參數放入列表中。 像這樣的東西。
ArrayList<List> listOfList = new ArrayList<List>();
String greetings = "hi";
int x = 0, y = 0, year = 0;
listOfList.add(Arrays.asList(greetings, x, y, year));
listOfList.add(Arrays.asList(greetings + " hello", ++x, ++y, ++year));
//Get and print list of the first list.
List listA = listOfList.get(0);
for(Object obj : listA) {
System.out.print(obj + " ");
}
System.out.println();
//Prints: "hi 0 0 0 "
//Print the second list.
System.out.println(listOfList.get(1));
//Prints: "[hi hello, 1, 1, 1]"
p.get(0)
會讓你得到列表中的第一個對象。
Java是面向對象的。 對象定義了你可以用它們做什么。 他們沒有“擁有”屬性,除非編寫該類的人決定它應該擁有它。
因此,如果沒有您問題中任何Object
的源代碼,您的問題是無法回答的。 大概它有一個返回它的.getSource()
方法。 如果是這樣: p.get(0).getSource()
將完成這項工作。 如果沒有,找到做那個工作的方法,如果它不存在,就寫它,如果你沒有寫那個類,那么你就做不到。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.