• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

parameter passing question for array reference

 
Bernd Stransky
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
following example works fine:
void m(long l) {}
....
int i=99; m(i); //numeric promotion
but why does this one not?
void m(long[] l) {}
....
int[] i={1,2,3}; m(i);
I get a compiler error message: "m(long[]) cannot be applied to (int[])"
BTW: If I use an assignment, the compiler error says 'Incompatible Types'.
I thought that assignment of arrays (which are references) work fine as long as the source type (int) can be converted to the destination type (long).
-Bernd
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Arrays containing primitives are special and are not treated like arrays containing references.
As you already know arrays are objects in Java, thus we have to do with a widening reference conversion issue.
From JLS 5.1.4 Widening Reference Conversions

The following conversions are called the widening reference conversions:
- blablabla
- From any array type SC[] to any array type TC[], provided that SC and TC are reference types and there is a widening conversion from SC to TC.

This is the key, int and long are not reference types.
 
Jennifer Wallace
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An array of references can only be converted into another array of references, if the reference types held by the arrays are convertible .
Doesnt work for primitive arrays !
 
Bernd Stransky
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for the info.
I guess I should start reading the JLS!
-Bernd
 
Bernd Stransky
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK,
so this works:
void m(Number [] n) {}
...
Integer I[] = { new Integer(1),new Integer(2)}
m(I);
:roll: Bernd
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes I wonder why though
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic