Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: One constructor or method that will accept array or set or list or ...?

In Java is there anyway to have one constructor that will accept an array or a collection? I have been fiddling with this for a while but I don't think it is possible.

I would like to be able to initialize MyClass, like this:

MyClass c = new MyClass({"rat", "Dog", "Cat"});

And like this:

LinkedList <String> l = new <String> LinkedList();
l.add("dog");
l.add("cat");
l.add("rat");
MyClass c = new MyClass(l);

This is what MyClass looks like. What can I make XXX be so that this will work? I know that I could overload the constructor, but if I can minimize code that would be awesome right?

public class MyClass{

   private LinkedHashSet <String> myList;

   public MyClass(XXX <String> input){
       myList = new LinkedHashSet <String> ();
       for(String s : input){
           myList.put(s);
       }

   }

}
like image 640
sixtyfootersdude Avatar asked Jul 11 '10 00:07

sixtyfootersdude


People also ask

How do you pass an array to a constructor in Java?

To pass an array to a constructor we need to pass in the array variable to the constructor while creating an object. So how we can store that array in our class for further operations.

How many parameters we can pass to constructor?

This method has four parameters: the loan amount, the interest rate, the future value and the number of periods.

How do you use constructors in an array?

Array constructor with a single parameterArrays can be created using a constructor with a single number parameter. An array with its length property set to that number and the array elements are empty slots.


1 Answers

You can declare two constructors and call second from first:

class MyClass {
    public MyClass(String... x) {
        // for arrays
        // this constructor delegate call to the second one
        this(Arrays.asList(x));
    }
    public MyClass(List<String> x) {
        // for lists
        // all logic here
    }
}

Calls would look like

new MyClass(new ArrayList<String>());
new MyClass("dog", "cat", "rat");
new MyClass(new String[] {"rat", "Dog", "Cat"});

Since there's only one line of code in the first constructor, it's pretty minimalistic.

like image 174
Nikita Rybak Avatar answered Sep 27 '22 23:09

Nikita Rybak