簡體   English   中英

違反檢查通用對象列表的方法

[英]Violate the method that checks a list of generic objects

這是來自Hyperskill.org的任務。

該任務的說明是;

您需要將實現添加到 Violator.defraud() 方法,該方法將執行以下操作:

根據方法簽名創建 Box 列表 將紙 object 放在列表中的至少一個 Box 中 結果列表應通過 NaiveQualityControl 檢查 您不應更改方法簽名或更改任何其他類的代碼,只需將實現添加到欺詐方法即可。

/* This class and its subclasses should pass quality check */
class Bakery {}

class Cake extends Bakery {}

/* But this should not */
class Paper {}

/* These boxes are used to pack stuff */
class Box<T> {
    void put(T item) { /* implementation omitted */ }
    T get() { /* implementation omitted */ }
}

/* This quality checker ensures that boxes for sale contain Bakery and anything else */
class NaiveQualityControl {

  public static boolean check(List<Box<? extends Bakery>> boxes) {
    /* Method signature guarantees that all illegal 
       calls will produce compile-time error... or not? */  
    return true;  
  }

}

這是實現的方法;

class Violator {

    public static List<Box<? extends Bakery>> defraud() {
        // Add implementation here
    }

}

到目前為止,我已經得到了這個;

public static List<Box<? extends Bakery>> defraud() {
        List<Box<? extends Bakery>> boxList = new ArrayList<>();

        Box<Paper> paperBox = new Box<>();
        Box<Bakery> bakeryBox = new Box<>();
        Box<Cake> cakeBox = new Box<>();

        boxList.add(bakeryBox);
        boxList.add(cakeBox);
        boxList.add(paperBox); // compile time error, required type <? extends Bakery>

        return boxList;
    }

顯然這不會運行。 我嘗試使用Object作為類型,但這超出了<? extends Bakery> <? extends Bakery> 我不能將paperBox<? extends Bakery <? extends Bakery Box類型。

您可以通過使用原始類型來解決它(通過刪除 boxList 的boxList )。 事實上,如果你這樣做,你可以添加幾乎任何類型的Object

public List<Box<? extends Bakery>> defraud() {
    List<Box<? extends Bakery>> boxList = new ArrayList<>();

    Box<Paper> paperBox = new Box<>();
    Box<Bakery> bakeryBox = new Box<>();
    Box<Cake> cakeBox = new Box<>();

    boxList.add(bakeryBox);
    boxList.add(cakeBox);

    List rawTypedList = boxList;    // Drop the generics to use raw types. 
    rawTypedList.add(paperBox);
    rawTypedList.add(new Object()); // Acutally, you can add any object, not just Boxes.

    return boxList;
}

但是,您會從編譯器或 IDE 收到使用原始類型的警告 - 這被認為是不好的做法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM