[英]How to add objects that use attributes from multiple info classes to an array list in main program?
[英]Storing Objects of multiple classes in an Array List, then accessing their attributes
我有(子)對象的 class
public class SubObjects {
int depth;
public SubObjects(int d) {
this.depth = d;
}
}
和一個 class 對象
public class Objects {
private int height;
private int width;
ArrayList<SubObjects> liste;
public Objects(int h, int w) {
this.height = h;
this.width = w;
this.liste = new ArrayList<>();
}
}
對象包含值高度和寬度以及子對象的 ArrayList。 這可以按預期工作,但是我確實想在這些 ArrayLists 中存儲來自不同類的多種類型的子對象。
經過一番谷歌搜索后,我將 Objects class 更改為
public class Objects {
private int height;
private int width;
ArrayList<Object> liste;
public Objects(int h, int w) {
this.height = h;
this.width = w;
this.liste = new ArrayList<Object>();
}
}
這允許我按照我的意圖將來自第二個 class SubObjects2 的對象存儲在 ArrayList 內
public class SubObjects2 {
int weight;
public SubObjects2(int weight) {
this.weight = weight;
}
}
這很棒,我以為我已經解決了,但后來我運行了主要的 class,而我使用早期的實現可以從 ArrayList 中的對象返回值
... liste.get(i).depth (in a for loop)
相同的查詢現在返回以下錯誤
Unresolved compilation problem:
depth cannot be resolved or is not a field
現在如何訪問存儲在 ArrayList 中的子對象內的值?
您的問題是Object
class 沒有名稱為depth
的字段,只有SubObject
具有此屬性
如果您的所有類型都有您想要獲取的公共屬性,您可以創建一個接口,並且所有類型都應該實現它,例如
interface SubObject {
int value();
}
public class SubObjects implements SubObject {
...
@Override
public int value() {
return depth;
}
}
public class SubObjects2 implements SubObject {
...
@Override
public int value() {
return weight;
}
}
現在您將創建一個子對象列表,在循環中,它將是
for (int i = 0; i < lists.size() ; i++) {
int value = lists.get(i).value();
}
另一種解決方案是在獲取值之前檢查類型並進行轉換
List<Object> lists = new ArrayList<>();
for (int i = 0 ; i < lists.size(); i++) {
Object object = lists.get(i);
if (object.getClass() == SubObjects.class) {
SubObjects subObject = (SubObjects) object;
int depth = subObject.depth;
}
else if if (object.getClass() == SubObjects2.class) {
SubObjects2 subObject2 = (SubObjects2) object;
int weight = subObject2.weight;
}
}
如果兩個類之間除了它們都擴展 Object class 之外沒有任何關系,所有對象都這樣做,並且您希望將這兩個類的對象存儲在同一個列表中,您可以將它們存儲在對象列表中。
在您可以訪問 object 的屬性之前,您需要將其轉換為您想要使用的類型。 這是在 generics 之前的做法。
List list = new ArrayList(List.of(Integer.valueOf(1), "hello"));
for(Object o: list){
if (o instanceof Integer){
System.out.println("o is an integer.");
Integer i = (Integer) o;
System.out.println(i.intValue());
} else if (o instanceof String){
System.out.println("o is a string.");
String s = (String) o;
System.out.println(s.length());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.