-1

I'm having a simple issue, this is the method:

void someMethod(Object... args)

When i'm using new String[]{"a", "b"} as parameter, i see two params in method : "a", "b" separately, however, when i'm using null, new String[]{"a", "b"}, param appearing as String array as expected.

Is there any way to transfer String array so it will be a String array in method using Objects... ?

Nik Myers
  • 1,843
  • 19
  • 28
  • by not using an array but some other structure (fx ArrayList) – Selvin Dec 15 '16 at 12:23
  • @Selvin, i'm currently using ArrayList, but i think it's an overkill to use it only for few strings, do you think it's not? – Nik Myers Dec 15 '16 at 12:23
  • @Selvin just compare : new String[]{"a", "b"} and ArrayList arrayList = new ArrayList<>(); arrayList.add("a"); arrayList.add("b"), even in case of lines of code it's far more – Nik Myers Dec 15 '16 at 12:25
  • *[If the last formal parameter is a variable arity parameter, the method is a variable arity method. Otherwise, it is a fixed arity method.](https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.1)* ... T... is only a syntactic sugar for a T[] ... so it would not be possible – Selvin Dec 15 '16 at 12:28
  • @Selvin, ok, thx, but just from your perpective, is it easier to user String[] with some dummy ignored object before it in the method itself, or call method from multiple places using ArrayList instead that would take a lot of lines unlike String[] – Nik Myers Dec 15 '16 at 12:30
  • 1
    or `new Object[] { new String[]{"a", "b"} }` – Selvin Dec 15 '16 at 12:31

1 Answers1

0

duplicate question from Can I pass an array as arguments to a method with variable arguments in Java?

Object... args is a syntactic sugar for a Object[]. when there is the null as first paramater and array as second he takes each as an object, but when there is an array of Strings he converts them to Objects.

Community
  • 1
  • 1
Ran Koretzki
  • 464
  • 3
  • 15
  • Thx for the reply, but i actually want to stick to @Selvin suggestion : new Object[] { new String[]{"a", "b"} } because it fits my needs – Nik Myers Dec 15 '16 at 12:36