-
Notifications
You must be signed in to change notification settings - Fork 181
faq 19431446
by Michael Zilske on 2014-09-30 08:42:34
Kai asks:
How do you convert typed Ids? I could get the following piece of code to compile:
@SuppressWarnings({ "cast", "unchecked", "rawtypes" }) private static Id<Vehicle> createVehicleIdFrom( Id<Person> id ) { return (Id<Vehicle>) (Id) id ; // weird. }Is that how it goes? I find in particular weird that I first need to convert Id<Person> to the untyped Id and only then to the newly typed Id<Vehicle; is that how it has to go? Thanks ...
Presumably better for this particular situation:
private static Id<Vehicle> createVehicleIdFrom( Id<Person> id ) { return Id.create(id.toString(), Vehicle.class) ; }??
by Michael Zilske on 2014-09-30 08:44:01
Marcel answers:
Id.create(personId, Vehicle.class)
One should create a new Id with the correct type. The Id class has a create method that accepts such an other Id.Reasoning for creating a new Id instead of casting: While it could be casted due to the generics being stripped away at compile time, the new Id implementation maintains a cache for Ids per type. Casting an Id circumvents that cache. So:
Id<Person> id1 = Id.create("1", Person.class); Id<Person> id2 = Id.create("1", Person.class);the two lines above will actually return the same object twice, thus id1 == id2 is true.
By casting, this would no longer be true, which might lead to strange errors later (e.g. objects not being found in a Map).
You are viewing an archive of the previous MATSim Q&A site. The real site is now at https://matsim.org/faq