Dan
Dan

Reputation: 2100

To HashMap or not to HashMap?

I am trying to create some code that will read information off of a text file. For example Bus_Routes.txtwill contain Route_A.txt 283,284 and from that the file Route_A.txt is opened and it contains 2 columns, Latitude Longitude with the coordinates listed. This I wrote out fine.

From this I am trying to get the device with id 283 to travel along the coordinates in sequence. I was recommended to use a HashMap. So my plan is to create a HashMap for the coordinates of Route_A.txt, have one column for Latitude and the other for Longitude. From that I was going to create another HashMap that will contain the device_id and the HashMap containing the coordinates, and the device_id will travel through each step of the HashMap.

Can this be done or am I completely looking in the wrong area? If anyone has any suggestions out there, they would be much appreciated

Upvotes: 1

Views: 237

Answers (2)

Brian Agnew
Brian Agnew

Reputation: 272217

Don't store your coordinates in a HashMap. It would be difficult to store multiple coordinates with the key (latitude?) being the same. e.g. a simple Map<Integer, Integer> would only hold one longitude value for a latitude, and that would prevent your route from having multiple destinations along the same longitude line.

I would rather use:

List<Coord>

where Coord is your lat/long pair. The List will preserve order, whereas a normal HashMap wouldn't.

Note that I'm deliberately encapsulating the lat/long pair as a specific object. You could store it as a tuple of integers but I'd rather a specific object to enforce typing, permitting addition of functionality etc. As noted elsewhere, Java is an OO language and you shouldn't shy from creating classes to represent these concepts (a sign that you should do this is when you create something like Map<String,List<Integer,Integer>>)

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 691635

A HashMap is a data structure that let's you associate a value with a key, and allows, given a key, to get back the value in constant time (without the need to loop as you would have to with a list or an array, for example).

So use this structure if your usecase needs such a functionality. Having devices stored in a map, where the device ID is the key, sounds like a good idea.

If, on the other hand, you want a data structure to contain fields (like latitude, longitude), then create a class. Java is an OO language. You should create your own classes. And if you want a list of coordinates, then you should use a List<Coordinate>, and not a HashMap.

Upvotes: 2

Related Questions