• 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

Methods with Generics

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There is a task which I don't unterstand



Possible Code
A) Object x = t.find(123, "456");
B) int x = t.find(123, new Double(456));
C) int x = t.find(123, new Integer(456));
D) int x = (int)t.find(new Double(123), new Double(456));

In my opinion C and D are valid.
In fact A and C are valid.

So, why is A correct?

I thought you define with the first parameter the type for the metho.
So, in C the type is defined by the first parameter -> int therefore the second parameter must be an Integer as well.
For the same reason, I thougt D was correct as well.

Can anyone explain that?

mfg alex
 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There seems to be some discrepancy in the method signature, but I'll assume it ought to be find(T x, T y)

Remember that the return type of the generic method is determined by the first common superclass of its parameters. If there is discrepancy, e.g. both could be Serializable too, the return type is determined by the assignment type.

A is correct because the first common supertype of Integer and String is Object, so the method signature becomes:

public Object find(Object x, Object y)

C is correct because both arguments are Integers (after autoboxing the first argument), and the return type of Integer can be autoboxed to an int

D is incorrect because whilst both arguments are Doubles, the return type of Double cannot be cast to an int.

Cheers,

Dave
 
Alexander Bell
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ok, I understand. It sounds plausible with your description

Thanks Dave
 
reply
    Bookmark Topic Watch Topic
  • New Topic