简体   繁体   中英

Data structure with index and two values in java

I have some data that I would like to organise, but I've found that a key-value data structure doesn't fit my requirements.

I have some data like this:

1    |  new CustomObject[] {...}
1    |  etc...
5    |  
8    |  
19   |  

Currently, I am putting the first column into a key, and the second into a value.

The issue I'm having is that when I'm putting new values into the key-value data structure, sometimes the values from one key get overriden since there are multiple values with the same key.

Ideally, the data structure I am looking for would have methods such as keyAt(int index) .

Does anyone know what sort of data structure could fit my requirements?

Since I am developing for Android, I have already looked at the documentation of Android's data structures like SparseArray<E> and ArrayMap<K, V> , however they are both key-value structures meaning that my key would be overriden when putting new values.

  • From my understanding, what you really want is something like an in-order array that has two values per index. What you could do based off of my understanding is have two parallel ArrayList s where one is the 'key' list and the other holds the values associated with the keys. You just have to make sure that when you add something to one, you also update the other. Another thing you could do is create a class where each instance of the class holds both the 'key' and its value.

    • The problem with these approaches is that you won't keep the ability to pull by key, but rather you'd have to pull by index and then check the key and value.
  • Another option is to have a HashMap<Key, List<value>> , so that each key has a list of the values associated with it.

    • The problem with this approach is that you'd either have to check for existence of a key then append to the existing list when adding a new element.

With the help of Pedro 's comment , I was able to find a solution for my particular use case.

Since I am using Android, I used the Pair<F, S> class (also available via the v4 Support Library) and a List<E> to help me achieve what I wanted.

I used:

List<Pair<Integer, CustomObject>>
class Key {
  public int hashCode() {
  /*terurn something*/
 }
}

Map<Key,ArrayList<V>>

What doesn't fit your requirements in this ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM