简体   繁体   中英

Invoke another class's method, passing object name as argument

New to Java, trying to code a basic traffic simulation where I have an Intersection class and an SimEngine (event list) class.

My Intersection class has a method called Arrival() indicating that a car has arrived at the intersection. As part of the method, I want to schedule a departure for that car at a timestamp 3 seconds later using the schedule() method in SimEngine.

The schedule() method takes four arguments: (What we're scheduling, the vehicle ID, the Intersection id, the timestamp). My question is about passing the Intersection id (this simulation has multiple intersections). If I don't know the name of the Intersection object's reference variable, how can I pass it to another function?

You need to identify the vehicles in your system first -- a common choice, especially in database driven applications, is to use a integer value. So attach an unique identifier to each of your vehicles, and then reference to them as an Integer or Long , depending on how many instances you foresee.

If you only hold the data in the memory, you can store and retrieve the vehicles from a Map<Integer,Vehicle> . Take extra precautions on thread safety here, ConcurrentHashMap is a good choice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM