简体   繁体   中英

How to refactor this HashSet in Java

I am new to Java. I have a method of HashSet, and wanted to know a better way of coding the following code:

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;
}

What is the most efficient way to do something like this?

I would use:

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")));

Of course, if you would never modify your set, the it would be more efficient if you had it as a constant:

 private static final Set<Guitar> GUITARS = 
   Collections.unmodifiableSet(new HashSet(Arrays.asList(
      ...

 public Set<Guitar> getGuitars() {
     return GUITARS;
 }

If you want to add all the elements to HashSet at the same time, you can use Arrays.asList . Check this question for reference :

Add multiple fields to Java 5 HashSet at once?

I would suggest to use Guava's 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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM