Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct usage of storing objects in maps

Say I need to store a collection of Student objects and each student has a unique id. One option is to store all of them in a list, but then when searching for a student, I'd have to perform a linear search and check their id's. The other option would be to use a map, of something like: Map where the keys are the student id's that map to the actual student objects.

Is this a sensible approach for the given problem? On the one hand it feels right because I can easily retrieve a student by their id, however, on the other hand, it feels like I'm slightly redundantly storing the id, which already exists within the student object - so I'm sort of storing it twice, but the key is the lookup mechanism.

My add would be something like:

public void add(Student s) {
     lookup.put(s.getId(), s);
}
like image 987
Tranquility Avatar asked Feb 01 '16 11:02

Tranquility


People also ask

When should we use Map?

Answer: Generally, we use maps as a reference to show political boundaries, landforms, water bodies, and the positions of cities. Maps also help us to know the routes of an area, landmarks, location (latitudes and longitudes) of a building or things, etc.

How do you compare object and Map?

Few basic differences are as follows: In Object, the data-type of the key-field is restricted to integer, strings, and symbols. Whereas in Map, the key-field can be of any data-type (integer, an array, even an object!) In the Map, the original order of elements is preserved.


1 Answers

May this redundancy be the only one you will ever encounter in programming.

The added value of using Map with unique object id, in terms of both performance and readability, is worth the small overhead incurred by such practice.

If you really feel this overhead is too much, the objects you put inside your Map data structure can be stripped of the ID property, and the ID property will only be used as the key, than, during retrieval, you can infer the ID from the map key.

like image 126
Fanchi Avatar answered Oct 20 '22 08:10

Fanchi