Eric Wilson
Eric Wilson

Reputation: 59435

Overloaded constructor ambiguity

I'm trying to use an overloaded constructor in Java that can accept either an int[] or a String. I'm getting a compile error, which seems to be indicating that in this constructor call would be ambiguous if the variable were a null string, or a null array.

Is there an easy way around this?

Upvotes: 5

Views: 2568

Answers (4)

Steve Reed
Steve Reed

Reputation: 2541

If you have control of the class you wish to instantiate, consider using a static factory method so you can give them two separate names and avoid the overloading-related confusion.

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

Otherwise, decide what your null represents: Is it a null array of ints, or a null string? It's possible that the class you are constructing behaves differently given one over the other. Once you know what your null represents, simply cast it to that type in the call to the constructor.

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

Lastly, it sounds like you might be passing an object reference to this constructor instead of an explicit null. Perhaps something you're getting from a java.util.Map. If so, you could test this object with instanceof and cast to the appropriate type before sending it on to the constructor in question.

Upvotes: 2

user85421
user85421

Reputation: 29730

maybe you can add a constructor without arguments.

Upvotes: 4

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

The easiest way - avoid null. If it's an empty String use ""; an empty int[] use new int[].

To answer the question you can use a cast or assign null to a variable:

new MyClass((String)null)

final String nullString = null;
new MyClass(nullString)

The former is generally preferred, if you are going to do it at all.

Upvotes: 5

Joachim Sauer
Joachim Sauer

Reputation: 308269

Cast the argument to one of the types:

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

Upvotes: 16

Related Questions