Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics Query Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Generics Query" Watch "Generics Query" New topic
Author

Generics Query

Nilesh Raje
Ranch Hand

Joined: Aug 02, 2005
Posts: 153
Hi Freinds,

How can this class be completely made to use Generics?

public class WhatDoIDo {
private X x;
private boolean b;
private Object o;

public WhatDoIDo(X x) {
this.x = x;
}

synchronized Object z() {
if (!b) {
o = x.y();
b = true;
}
return o;
}

public interface X {
Object y();
}
}

Thanks
Punit Singh
Ranch Hand

Joined: Oct 16, 2008
Posts: 952


[EDIT: I did not see interface name is also using X here].

I also do not know the purpose of this program, I think this code should not be generalized legally, as this code has nothing to do with type parameter T, putting T as type parameter is just a waste here and of no use.


SCJP 6
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 16696
    
  19


This shouldn't compile. The interface T, defined at line 18, is not the same type passed to the generic... hence, line 12 will get a type error.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Nilesh Raje
Ranch Hand

Joined: Aug 02, 2005
Posts: 153
So what is the right Approach?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 16696
    
  19

Nilesh Raje wrote:So what is the right Approach?



Let's start with... What is the problem that you are trying to solve? Generics is a tool, that is used to solve problems. Taking perfectly running code, and adding generics, just to add generics, doesn't make sense.

Henry
Nilesh Raje
Ranch Hand

Joined: Aug 02, 2005
Posts: 153
Well i was given this code in a test and just asked to make it use generics.

I would appreciate if you could t tell me what is wrong with the code? What do you think the code is actually doing? Now thats making me think good point!
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Generics Query
 
Similar Threads
Generics
generics
generics
Generics
Generics