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:
- Prevents duplicate items (I need to be able to prevent a scanned Bluetooth device to not repeatedly enter the list.)
- Provides easy access to items for updating values.
And the following pitfalls:
- Not supported naturally by the
BaseAdapter
class? I cannot seem to retrieve elements usinggetItem
for a customListView
Adapter
.
However with an ArrayList
- I can easily access items via their indices.
- Can easily replace items for updating values.
Works easily with custom
BaseAdapter
class. But...I receive duplicated items.
- I cannot easily compare or check with the
ArrayList.contains
method unless I implement some customcomparators
of theArrayList
's objects' parameters.
Is there an easier way to achieve the following:
- Scan via BLE, construct a custom object from the scan results. (already complete).
- Stick that custom object in an array list if it isn't already in it.
- If it is already in the array list, replace the previous object with the new one?
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()
andObject.hashCode()
. These are used internally inArrayList.contains()
. This would give you no duplicated entries with adding only items wherelist.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.