簡體   English   中英

如何在Java中將對象添加到集合中?

[英]How can I add an object into a set in Java?

我正在為公交車站編寫一些JUnit測試,但在嘗試創建要通過測試使用的對象時遇到了麻煩:

public class StopTests {
  BusRoute rte = new BusRoute("250");
  Set<BusRoute> set = new Set<BusRoute>();
  BusStop stop = new BusStop(00000, "Staples Center", 90.0, 90.0, set);
...
}

我的問題是測試無法編譯,因為Eclipse表示無法實例化“ new Set()”。 我的意圖是將“ rte”添加到“ set”中,以便可以在沒有編譯錯誤的情況下創建“ stop”,但是我對如何執行此操作感到困惑。 我試圖接近它:

public class StopTests {
  BusRoute rte = new BusRoute("250");
  Set<BusRoute> set = new Set<BusRoute>();
  set.add(BusRoute rte);
  BusStop stop = new BusStop(00000, "Staples Center", 90.0, 90.0, set);
...
}

但是Eclipse給了我另一個錯誤,關於“添加”之后沒有標識符。

解決此問題的最佳方法是什么?

編輯:這就是我現在所擁有的:

public class StopTests {
  BusRoute rte = new BusRoute("250");
  Set<BusRoute> set = new HashSet<BusRoute>();
  set.add(rte);
  BusStop stop = new BusStop(00000, "Staples Center", 90.0, 90.0, set);
...
}

Set是一個接口,因此無法創建它的實例。 您需要創建Set實現的實例,例如HashSet

嘗試更改此:

Set<BusRoute> set = new Set<BusRoute>()

Set<BusRoute> set = new HashSet<BusRoute>()

另外,要在集合中添加元素,您需要在集合實例而不是BusRoute實例上調用add 所以改變這個:

  rts.add(BusRoute rte);

  set.add(rte);

您的問題是: rts.add(BusRoute rte) 你並不需要預先rte和它的類型:使用rts.add(rte)來代替。

Set是一個接口,您需要使用一個實現類實例化:

Set<BusRoute> set = new HashSet<BusRoute>()

請查看這些鏈接

設置例子

設定API

干杯!

Set是抽象的,因此無法實例化。 您需要使用Set的實現,例如HashSet

public class StopTests {

    public void someMethod() {
        BusRoute rte = new BusRoute("250");
        Set<BusRoute> set = new HashSet<BusRoute>();
        set.add(rte);
        BusStop stop = new BusStop(00000, "Staples Center", 90.0, 90.0, set);
        ...
    }
}

暫無
暫無

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

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