LinkedHashMap vs ArrayList with Bluetooth Scanning and ListView

79 views Asked by At

I have a little bit of a confusion when it comes to what is considered the better implementation.

One the one hand,

LinkedHashMap provides the following benefits:

  1. Prevents duplicate items (I need to be able to prevent a scanned Bluetooth device to not repeatedly enter the list.)
  2. Provides easy access to items for updating values.

And the following pitfalls:

  1. Not supported naturally by the BaseAdapter class? I cannot seem to retrieve elements using getItem for a custom ListView Adapter.

However with an ArrayList

  1. I can easily access items via their indices.
  2. Can easily replace items for updating values.
  3. Works easily with custom BaseAdapter class. But...

  4. I receive duplicated items.

  5. I cannot easily compare or check with the ArrayList.contains method unless I implement some custom comparators of the ArrayList's objects' parameters.

Is there an easier way to achieve the following:

  1. Scan via BLE, construct a custom object from the scan results. (already complete).
  2. Stick that custom object in an array list if it isn't already in it.
  3. If it is already in the array list, replace the previous object with the new one?
1

There are 1 answers

0
JacksOnF1re On BEST ANSWER

As nobody seems to answer, I will provide my approach.

1. Duplicated entries

If you like to use a List , then as I stated out in the comments, I would let your Item class override Object.equals() and Object.hashCode(). These are used internally in ArrayList.contains(). This would give you no duplicated entries with adding only items where list.contains(item) == false.

2. Sorting

To sort a List, there is the very usefull class called Collections, which sorts a list simply with the static method Collections.sort(). To make this work you need to implement the Comparable interface in your item class and apply your own sorting rules here.

TreeSet

If it does not necessarily needs to be a List, I would recommend to implement Comparable and use a TreeSet, which gives you by the nature of a set no duplicated entries and is sorted directly by adding.

LinkedHashSet

If you only need no duplicated entries and the order should followed by the order of insertion, go with LinkedHashSet.

Best wishes, Steve.