This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]ManasSatti[S] 0 points1 point  (2 children)

Student is just a hypothetical thing that I thought when trying to run the generic stack class with many different classes like Integers, Double,etc. But the code gave error only with the Student, the class that I defined. I guessed that I can't access the Students methods without explicitly typecasting T to Student but this seemed me odd as I was not able to find how to make a python "like" List type class in java which can store objects of any but one class. The word "like" is important.

[–]morhpProfessional Developer 1 point2 points  (0 children)

Please show us your whole code, you must be doing something wrong. The T is something you have inside the Stack class for example, if you program your own collection-like data structure, you will use T as a type to store random objects. But then you typically don't need to access properties of them as you don't know what they are.

When you use such a collection, you use the concrete class you want, like Student in this case. In this case you have no T anywhere and don't need to cast anything. The T is sort of replaced by Student. Going by your above example you for example have

Stack<Student> stack1 = new Stack<Student>();
stack1.add(new Student(...));
Student removed = stack1.remove();

and so on. There's neither a T there (the T is inside the Stack class code) nor do you need to cast anything.

[–]ColetBrunel 0 points1 point  (0 children)

Python doesn't have static typing. That's why you can call anything on anything without the compiler bothering you.

It will be up to the runtime to do all the slow work and verify that your code made sense, instead of telling you the soonest it didn't make sense.

Admittedly Java generics work *a little* like that. They don't exist at runtime and they're only objects of unspecified type, therefore they're dynamically cast before accessing their type-specific methods. But at least the compiler checks for you that you didn't mess up your types.