Overloaded constructor ambiguity

I am trying to use an overloaded constructor in Java, which can accept either int[]or String. I get a compilation error that seems to indicate that in this constructor call it will be ambiguous if the variable was a string nullor an array null.

Is there an easy way around this?

+5
source share
4 answers

Passing an argument to one of the types:

Foo f1 = new Foo((int[]) null);
// or
Foo f2 = new Foo((String) null);
+16
source

The easiest way is to avoid null. If it is empty String, use ""; int[]use empty new int[].

, null :

new MyClass((String)null)

final String nullString = null;
new MyClass(nullString)

, .

+5

, .

+4

, , factory, , .

public static Foo createFromIntArray(final int[] ints) { ... }
public static Foo createFromString(final String str) { ... }

, null: ints ? , , , -, . , null, .

new Foo((String) null);
new Foo((int[]) null);

, , null. , java.util.Map. , instanceof .

+2

All Articles