Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Object[] and Object

 
Anthony Karta
Ranch Hand
Posts: 342
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why we canNot pass String[] to Object[] in method argument such as

anyArrayType(new String[] {"a", "b"} );

void anyArrayType(Object[] o) { }

//void anyArrayType(Object o) { } // this one work

BUT...

It is working in variable assignment such as

Object[] o1 = new String[] {"a", "b"};
Object o2 = new String[] {"c", "d"};

thanks
 
Charith Fernando
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the error you are getting? please post the compilation error if you're getting any....
 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Seems to work fine for me.

 
Anthony Karta
Ranch Hand
Posts: 342
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry guys.

I tried with "primitive" type such as:

anyArrayType(new short[] {5,8});

why it works for Wrapper classes??

thanks again
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think Anthony is asking about overloading here. Anthony do you mean having both anyArrayType method definitions at the same time?
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Anthony Karta:
Sorry guys.

I tried with "primitive" type such as:

anyArrayType(new short[] {5,8});

why it works for Wrapper classes??

thanks again


It works because arrays of wrapper class objects are arrays of Objects too.
 
Anthony Karta
Ranch Hand
Posts: 342
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Barry Gaunt:


It works because arrays of wrapper class objects are arrays of Objects too.


well, I'm expecting short[] array will be autoboxed to Short[] by JVM, but the code even not compile.

do more testing:

short[] shortArray = new short[] {5,8} ;

Object[] oo = (Short[]) shortArray; // Not compiled here

how to convert primitive array to Wrapper array then?

this whole array thing make me confuse. Seems autoboxing doesn't work the same way as non-array reference variable, such as below:

short shortVar = 5;
Short shortWrapper = shortVar; // worked !
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What you are expecting is not possible. A short[] will not be autoboxed into a Short[]. Autoboxing only applies to the primitive and its corresonding wrapper class (eg. short -> Short).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic