我正在做一個作業,我只能將特定類添加到通用 ArrayList,但 ArrayList 似乎沒有按預期添加類。public class ComputerOrder<T extends Product> extends GenericOrder<T> {private List<T> products;//the list of items public void addProduct(T t) { if (t.getClass().isInstance(ComputerPart.class)) { products.add(t); } if (t.getClass().isInstance(Service.class)) { products.add(t); } if (t.getClass().isInstance(Peripheral.class)) { products.add(t); } else System.out.println("Not the right type of object."); }主要參數測試:public static void main(String[] args) { ComputerPart c; c = new ComputerPart(12); ComputerOrder<Product> g3 = new ComputerOrder<>(); g3.addProduct(c); g3.print();}預期的結果是 ArrayList g3 能夠添加 c,因為它是 ComputerPart 對象的一個實例,但 ArrayList 是空的。有人可以解釋我的代碼做錯了什么嗎?注意:“else”語句僅用于測試目的,并且似乎表明 if 語句無法正常工作,因為它在我測試時不斷被觸發。
1 回答

慕婉清6462132
TA貢獻1804條經驗 獲得超2個贊
您的主要問題是您弄亂了 isinstance 檢查。該方法是相反的;你要找的是:
ComputerPart.class.isInstance(t)
,不是t.getClass().isInstance(ComputerPart.class)
。但是,您可以將其寫得更簡單t instanceof ComputerPart
:
其次,您搞砸了系統輸出。據推測,您的意思是代碼中的每個“if”都改為“else if”,當然第一個除外。
添加回答
舉報
0/150
提交
取消