简体   繁体   中英

Hashset as constructor argument in Java

is there any way I can declare constructor to take HashSet as one of arguments and then pass HashSet value directly as argument during object initialization? I mean something like this:

public class Order {
    private Set<Product> products = new HashSet<Product>();
    public Order (???) {
    this.products = ???
    }
}

and then, while initializing object:

Order order = new Order("product1", "product2", "product3");

is it possible?

You can use varargs :

public class Order {
    private Set<Product> products;
    public Order (Product... products) {
       this.products = new HashSet<Product> (Arrays.asList(products));
    }
}

But then you pass to the constructor Product instances :

Order order = new Order(new Product("product1"), new Product("product2"), new Product("product3"));

I would recommend something like:

public class Order {
    private final Set<String> strings;

    public Order(final Set<String> strings) {
        this.strings = strings;
    }

    public Order(final String... strings) {
        this(toSet(strings));
    }

    private static Set<String> toSet(String[] strings) {
        final Set<String> ss = new HashSet<>();
        for (final String s : strings) {
            if (!ss.add(s)) {
                throw new IllegalArgumentException("Duplicate string " + s);
            }
        }
        return ss;
    }
}

This takes a varargs argument, which allows you to invoke the constructor as you would like.

It also checks for duplicates during initialization, I would suggest that duplicates are an error; but you could just log it and carry on.

The above looks to me like you want a constructor taking varargs of String type, and then create the HashSet via those varargs.

A HashSet can't be created via varargs, so perhaps create the set and then add each element in turn. Or create a collection of those vararg elements, and then construct the HashSet directly from that.

If you really need to use the HashSet in the constructor, I would do something like this in the constructor:

public Order (HashSet<String> myHashSet)

Then, whenever you want to initialise it, call it this way:

Order order = new Order(new HashSet<String>(Arrays.asList("product1", "product2")));

It's not very time efficient, but it works.

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