Java: one constructor or method that will take an array or set or list or ...?

In Java, is there anyway one constructor that will accept an array or collection? I have been doing this for some time, but I do not think it is possible.

I would like to be able to initialize MyClass, for example:

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 do XXX so that it works? I know that I can overload the constructor, but if I can minimize code that would be terribly right?

public class MyClass{

   private LinkedHashSet <String> myList;

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

   }

}
+5
source share
5 answers

You can declare two constructors and call the second one 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 will look like

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

, .

+20

MyClass1 {

    public MyClass1(final String... animals) {
        for (final String animal : animals) {
            System.out.println("eat " + animal);
        }
    }

    public static void main(final String[] args) {
        new MyClass1();
        new MyClass1("dog", "cat", "rat");
        new MyClass1(new String[] { "dog", "cat", "rat" });
    }
}

public class MyClass2 {

    public MyClass2(final Iterable<String> animals) {
        for (final String animal : animals) {
            System.out.println("eat " + animal);
        }
    }

    public static void main(final String[] args) {
        new MyClass2(Arrays.asList("cat", "rat", "dog", "horse"));
        final LinkedList<String> animals = new LinkedList<String>();
        animals.add("dog");
        animals.add("house");
        animals.addAll(Arrays.asList("cat", "rat"));
        new MyClass2(animals);
    }
}
+1

, , . , . , :

Foo[] foos = ...
for (Foo foo : foos)

. : Iterable?

+1

:

MyClass(Object args) {
    if (args instanceof List) {
        ...
    } else if (args instanceof Set) {
        ...
    } else if (args.getClass().isArray()) {
        ...
    } else {
        thrown new IllegalArgumentException("arg type is wrong");
    }
}

IMO, API, . ( . Collection Object.)

, .

, ( ) Java, :

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

; .

String[] foo = {"rat", "Dog", "Cat"};

; .

String[] foo = new String[]{"rat", "Dog", "Cat"};
String[][] bar = new String[][]{{"rat", "Dog", "Cat"}, /* ... */};
+1

, Arrays.asList, , .

.

0

All Articles