Which data structure should I use based on my needs?

It is required:

  • Saving objects of a class that overrides values ​​and a hash code
  • Will loop and move objects into the data structure
  • You must be able to call contains to check if any object is stored in the structure.
  • If contains returns true, select this object from the structure and call a specific getter for this object

Parameters that I reviewed:

  • Map - this works for all needs, but in fact I don’t have a map (key and value). all i have is a bunch of objects. Would it be good practice to forcibly use a card, storing objects as a key and an integer, or something in value?

  • Set will work, however it does not have a fetch method like get.

  • The list will also work, but it does not have an index-based retrieval method. The value, as soon as contains returns true, I will have to iterate over the list to find the index of my specific object, and then extract it.

I am open to using different libraries like apache commons or guava for example.

+4
source share
3 answers

The list will also work, but it does not have an index-based retrieval method.

List has an indexOf(Object) method that will do exactly what you want.

+2
source

Although the best thing to use in this scenario would be Map , as it offers a quick search based on a Key-Value pair.

But List also allows index-based data retrieval.

So you can use either List or Map . But to make your task easier, I would prefer Map . Since in the case of Map you do not need to search for the index object, then get the Object at that index. Retrieval is just a one-line operation.

 // When using a List. List<String> myList = new ArrayList<String>(); if (myList.contains("rohit")) { myList.get(myList.indexOf("rohit")); } // When using Map. Map<String, String> myMap = new HashMap<String, String>(); // You can directly fetch your object, based on some Key if you have one.. myMap.get("key"); 
+2
source

You need a kit. You don’t need a sampling method (what do you think you do) because, as you said, you only have a bunch of objects. And since they use equals and hashCode , the set is exactly what you need.

Of course, a map might also work, because its keys are also a set, but in the end you need to better indicate your requirements, as it seems you are a little confused about your data structure. As I understand it, you really don't need a map.

A hash set implementation will be implemented. Here is what you can do with all of this:

 class Foo { final String name; Foo(String name) { this.name = name; } boolean equals(Object obj) { return (obj instanceof Foo) && ((Foo)obj).name.equals(name); } } Set<Foo> fooSet = new HashSet<Foo>(); fooSet.add(new Foo("someFoo")); assert fooSet.contains(new Foo("someFoo")); 
-2
source

Source: https://habr.com/ru/post/1439361/


All Articles