[英]How can I add an object into a set in Java?
I am writing some JUnit tests for a bus stop but I am having trouble trying to create objects to be used through the tests: 我正在为公交车站编写一些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);
...
}
My problem is that the test won't compile because Eclipse says "new Set()" cannot be instantiated. 我的问题是测试无法编译,因为Eclipse表示无法实例化“ new Set()”。 My intention is to add 'rte' into 'set' so that 'stop' can be created without compilation errors, but I am stumped on how to do this.
我的意图是将“ rte”添加到“ set”中,以便可以在没有编译错误的情况下创建“ stop”,但是我对如何执行此操作感到困惑。 I tried approaching it like:
我试图接近它:
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);
...
}
but Eclipse gave me another error about not having an identifier following 'add'. 但是Eclipse给了我另一个错误,关于“添加”之后没有标识符。
What would be the best way to approach this? 解决此问题的最佳方法是什么?
EDIT: This is what I have now: 编辑:这就是我现在所拥有的:
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
is an interface so cannot create an instance of it. Set
是一个接口,因此无法创建它的实例。 You need to create and instance of Set implementations such as HashSet
. 您需要创建Set实现的实例,例如
HashSet
。
Try changing this: 尝试更改此:
Set<BusRoute> set = new Set<BusRoute>()
to 至
Set<BusRoute> set = new HashSet<BusRoute>()
Also to add the element in set you need to call add
on set instance and not on BusRoute
instance. 另外,要在集合中添加元素,您需要在集合实例而不是
BusRoute
实例上调用add
。 So change this : 所以改变这个:
rts.add(BusRoute rte);
to 至
set.add(rte);
Your issue here is with this line: rts.add(BusRoute rte)
. 您的问题是:
rts.add(BusRoute rte)
。 You don't need to prepend rte
with its type: use rts.add(rte)
instead. 你并不需要预先
rte
和它的类型:使用rts.add(rte)
来代替。
Set
is an interface, you need to instantiate with an implementation class: Set
是一个接口,您需要使用一个实现类实例化:
Set<BusRoute> set = new HashSet<BusRoute>()
Please see these links 请查看这些链接
Cheers !! 干杯!
Set
is abstract so it cannot be instantiated. Set
是抽象的,因此无法实例化。 You need to use an implementation of Set
, such as HashSet
. 您需要使用
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.