亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將多個類添加到通用 ArrayList?

如何將多個類添加到通用 ArrayList?

偶然的你 2022-12-15 17:05:16
我正在做一個作業,我只能將特定類添加到通用 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”,當然第一個除外。


查看完整回答
反對 回復 2022-12-15
  • 1 回答
  • 0 關注
  • 74 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號