我有一類(子)物件
public class SubObjects {
int depth;
public SubObjects(int d) {
this.depth = d;
}
}
和一類物件
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。這按預期作業,但是我確實想在這些 ArrayList 中存盤來自不同類的多種型別的子物件。
經過一番谷歌搜索后,我將 Objects 類更改為
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>();
}
}
這允許我按照我的意圖從 ArrayList 中的第二個類 SubObjects2 存盤物件
public class SubObjects2 {
int weight;
public SubObjects2(int weight) {
this.weight = weight;
}
}
這很棒,我以為我已經解決了它,但是后來我運行了主類,而我在早期的實作中可以使用來自 ArrayList 中的物件的 getter 回傳值
... liste.get(i).depth (in a for loop)
相同的查詢現在回傳以下錯誤
Unresolved compilation problem:
depth cannot be resolved or is not a field
現在如何訪問存盤在 ArrayList 中的子物件中的值?
uj5u.com熱心網友回復:
你的問題是這個Object類沒有名字的欄位,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;
}
}
uj5u.com熱心網友回復:
如果兩個類之間沒有關系,除了它們都擴展了所有物件所做的 Object 類,并且您想將這兩個類的物件存盤在同一個串列中,您可以將它們存盤在一個物件串列中。
在您可以訪問物件的屬性之前,您需要將其強制轉換為您要使用的型別。這是在泛型之前完成的方式。
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());
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/386787.html
