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);
}
}
}
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.
This method has four parameters: the loan amount, the interest rate, the future value and the number of periods.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With