• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

generic class and how to pass type to them

 
Jean Perry
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4181
21
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Mansukhdeep Thind
Ranch Hand
Posts: 1158
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?


 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic