aspose file tools*
The moose likes Beginning Java and the fly likes generic class and how to pass type to them Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "generic class and how to pass type to them" Watch "generic class and how to pass type to them" New topic
Author

generic class and how to pass type to them

Jean Perry
Greenhorn

Joined: Mar 12, 2013
Posts: 6
I'm working with generics, but I'm not sure if I fully understand them, so if someone can confirm what I am thinking of is correct then that would be really helpful.

lets say I have a generic class:


then I create a non-generic class called "Students", and basically the MyArrayList class will be populated by student objects. then I also have


now, if i want to pass something to the arraylist of students like a grade; which would be an Integer type. how might I achieve that? I was using



would java automatically fit the generic class to an Integer if I just pass it a random number? or would I have to use some kind of Wrapper...but doesn't java have auto boxing and auto unboxing if that is the case?
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4174
    
  21

Jean Perry wrote:

now, if i want to pass something to the arraylist of students like a grade; which would be an Integer type. how might I achieve that?

You can't - you are saying your list takes Students, so it takes Students. Since an Integer or a Grade is not a Student, you can't put it in the list. Put more importantly - do you actually want to? Does the Grade belong in a collection of Students? Or does the Grade belong to a particular Student in the collection?


Steve
Mansukhdeep Thind
Ranch Hand

Joined: Jul 27, 2010
Posts: 1157

I'm working with generics, but I'm not sure if I fully understand them, so if someone can confirm what I am thinking of is correct then that would be really helpful.

lets say I have a generic class:


Hi Jean

A very warm welcome to the ranch. You are correct. You have not understood generics correctly or completely. It takes time. First of all , there is nothing such as a "generic class". You have "generic types" that a class defines as it's parametrized type<inside angular brackets>. For example, in your case, the generic type will be "Student". What that means to the compiler is "this ArrayList will only hold objects of type Student". You try adding any other type of object and you shall get a compile time error.

P.S--> I would suggest that you devote some time to studying the concept again. Not down the things that you don't understand and come back with doubts. Which book are you learning Java from?



~ Mansukh
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: generic class and how to pass type to them