• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

get objects of the certain type from Collection

 
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
there is an error in the code

should be:


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

 
Sheriff
Posts: 22701
129
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 ]
 
Kuba Zygmunt
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Great !

Thank you for showing me this approach
 
We don't have time for this. We've gotta save the moon! Or check this out:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic