• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

11 K&B questions. Question 5

 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
My question here is, why the doX(long...x) is not called for
doX(short,short)

If I change doX(long...x) for doX(long,long) it's called. (And it's nice according to rules I've learned )
And if I delete the doX of the integers and Numbers it is also called.

And thinking about this I have another question.
In general if I have
m(A a1,A a2,A a3)
and m(A ...a)

and I call with m(a,a,a) the first is selected, isn't it? The rule is that if there multiple alternatives the novarargs wins?

A lot of thanks in advance,

The question is:
Given:


class Eggs {
int doX(Long x, Long y) { return 1; }
int doX(long... x) { return 2; }
int doX(Integer x, Integer y) { return 3; }
int doX(Number n, Number m) { return 4; }

public static void main(String[] args) {
new Eggs().go();
}
void go() {
short s = 7;
System.out.print(doX(s,s) + " ");
System.out.println(doX(7,7));
}
}

What is the result?

A). 1 1
B). 2 1
C). 3 1
D). 4 1
E). 1 3
F). 2 3
G). 3 3
H). 4 3

CORRECT: H

Question copyrighted Kathy sierra & Bert Bates

 
Ranch Hand
Posts: 220
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
the compiler matches in this way
1. see if there's a match available straight away, if there is, done;
2. if not, autobox/unbox everything and see if there's a match, if there is, done;
3. if not, then try the varargs, if there is, done,
if not, there is a compile error.

Also note that suppose at any step, two or more methods match, a compile time error occurs
reply
    Bookmark Topic Watch Topic
  • New Topic