wood burning stoves 2.0*
The moose likes Java in General and the fly likes get objects of the certain type from Collection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "get objects of the certain type from Collection" Watch "get objects of the certain type from Collection" New topic
Author

get objects of the certain type from Collection

Kuba Zygmunt
Ranch Hand

Joined: Jul 17, 2007
Posts: 37
Hi,

Below you can see a simple hierarchy of Bike's family.


So, I have a Collection<Bike> and I would like to get all bikes of the certain type. What I've done is :


so I compare classes ( I dont want to use instanceof because I'm interested in a concrete class ( not superclass ).

Another way to do it is to create a BikeType class which stores and defines all used type of bikes, and then a super class Bike will have an additional field
BikeType bikeType;

and then I could compare bikes in collection using that property .
I dont know if the 2nd option is better, because when you add new class you will have to change bikeType.

What's your opinion ?
Kuba Zygmunt
Ranch Hand

Joined: Jul 17, 2007
Posts: 37
there is an error in the code

should be:

if (bike.getClass() == bikeType.getClass())
newList.add(booking);
}
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19684
    
  20

I'd go with a slightly modified version of your original code:

Of course this allows also non-bike classes to be passed.

So another modification, to allow only the Bike class and its subclasses:

There is another improvement to be made now: you know that everything inside the collection will be of the given type. So:


You can now do stuff like this:

[ November 22, 2007: Message edited by: Rob Prime ]

SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Kuba Zygmunt
Ranch Hand

Joined: Jul 17, 2007
Posts: 37
Great !

Thank you for showing me this approach
 
jQuery in Action, 2nd edition
 
subject: get objects of the certain type from Collection