Hashset as constructor argument in Java

泄露秘密 提交于 2021-02-05 07:47:47

问题


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?


回答1:


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



回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/29588997/hashset-as-constructor-argument-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!