• Post Reply Bookmark Topic Watch Topic
  • New Topic

Question regarding generics  RSS feed

 
Unnar Björnsson
Ranch Hand
Posts: 164
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all, I have question. Say I have a super class called Super and two subclasses called Sub1 and Sub2. I also have two ArrayLists for each type of the subclasses. Now I'm wondering if I can have a single method that puts the argument of type Super into the correct list, like this:


Is there a way to get around having to cast item to the correct subtype as item is guaranteed to be of the correct type if it passes the if statement. Is this a safe way to perform this task?
 
Jim Hoglund
Ranch Hand
Posts: 525
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you do not need to cast "item" because you
know that it will be placed in the correct list.
... Jim`...
 
Unnar Björnsson
Ranch Hand
Posts: 164
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jim Hoglund wrote:Yes, you do not need to cast "item" because you
know that it will be placed in the correct list.
... Jim`...


I get a compile error if I don´t cast it.
 
Hetal Vora
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can remove the strict typing for the ArrayList
ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList();

In this case, teh casting would not be required. But it would generate a compiler warning saying unchecked operation. The program will execute though.
 
Aditya Kanitkar
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I really havent understood the question...
 
Kulbir Java
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I feel we can think like this way.

you have a super class called Person
you have two subclasses called Driver and Teacher (both extends Person)

Now, Driver and Teacher cannot be cast into one anoteher, because a Driver IS-NOT a Teacher and Teacher IS-NOT a Driever but both are Persons.

You can have a method whcih accepts the list of Person and can add both Driver and Teacher to Person class. But you can not have any single method that can take a single list and add appropriately in the Driver and Teacher without casting.

Hope this help.

Regards
Kulbir
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!