How to refactor this HashSet in Java

I'm new to Java I have a HashSet method. I want to know a better method to encode 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","1922");
    Guitar guitar7 = new Guitar("Fender","1999");
    Guitar guitar8 = new Guitar("Fender","1986");
    Guitar guitar9 = new Guitar("Fender","1933");
    Guitar guitar10 = new Guitar("Fender","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 effective way to do such a thing?

Solution

I can use:

return new HashSet(Arrays.asList(
    new Guitar("Gibson","1987"),new Guitar("Gibson","1976"),"1978"),"1967"),"1967")));

Of course, if you will never modify your collection, it will be more effective if you treat it as a constant:

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

 public Set<Guitar> getGuitars() {
     return GUITARS;
 }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>