我是Java新手。我有一个HashSet方法,想知道编写以下代码的更好方法:
public HashSet<Guitar> getGuitars() {
HashSet<Guitar> guitarInformations = new HashSet<Guitar>();
Guitar guitar1 = new Guitar("Gibson", 100, "1987");
Guitar guitar2 = new Guitar("Gibson", 200, "1976");
Guitar guitar3 = new Guitar("Gibson", 300, "1978");
Guitar guitar4 = new Guitar("Gibson", 400, "1967");
Guitar guitar5 = new Guitar("Gibson", 500, "1967");
Guitar guitar6 = new Guitar("Fender", 100, "1922");
Guitar guitar7 = new Guitar("Fender", 200, "1999");
Guitar guitar8 = new Guitar("Fender", 300, "1986");
Guitar guitar9 = new Guitar("Fender", 400, "1933");
Guitar guitar10 = new Guitar("Fender",500, "1988");
guitarInformations.add(guitar1);
guitarInformations.add(guitar2);
guitarInformations.add(guitar3);
guitarInformations.add(guitar4);
guitarInformations.add(guitar5);
guitarInformations.add(guitar6);
guitarInformations.add(guitar7);
guitarInformations.add(guitar8);
guitarInformations.add(guitar9);
guitarInformations.add(guitar10);
return guitarInformations;
}
做这样的事情的最有效方法是什么?
答案 0 :(得分:4)
我会用:
return new HashSet(Arrays.asList(
new Guitar("Gibson", 100, "1987"),
new Guitar("Gibson", 200, "1976"),
new Guitar("Gibson", 300, "1978"),
new Guitar("Gibson", 400, "1967"),
new Guitar("Gibson", 500, "1967")));
当然,如果你永远不会修改你的设置,那么如果你把它作为一个常数会更有效:
private static final Set<Guitar> GUITARS =
Collections.unmodifiableSet(new HashSet(Arrays.asList(
...
public Set<Guitar> getGuitars() {
return GUITARS;
}
答案 1 :(得分:2)
如果要同时将所有元素添加到HashSet,可以使用Arrays.asList。请查看此问题以供参考:
答案 2 :(得分:1)
我建议使用Guava&#39; ImmutableSet Builder
public static final ImmutableSet<Guitar> GUITARS= ImmutableSet.of(
new Guitar("Gibson", 100, "1987"),
new Guitar("Gibson", 200, "1976"),
new Guitar("Gibson", 300, "1978"),
new Guitar("Gibson", 400, "1967"),
new Guitar("Gibson", 500, "1967"));