2

Lets say I have a list of keys that all contain an Object like this:

2, 4, 5, 9, 11

I need them to be ordered because I want to do something like:

function Object[] getObjectsAfter( int i ); 
// so 4 would result in an array of objects in the keys 5, 9 and 11 

and

function Object[] getObjectsBefore( int i ); 
// so 4 would result in an array of objects in the keys 2 

What collection is best to use in Android? I tried SparseArray and TreeMap, but I can't find a way to iterate from a certain point.

5
  • Have you tried a HashMap?
    – Marcus
    Jan 20, 2015 at 11:16
  • What about LinkedList ?
    – Rami
    Jan 20, 2015 at 11:18
  • Are there duplicates? Do you need a map, or just a collection of these keys?
    – aioobe
    Jan 20, 2015 at 11:21
  • If you do not requires key-value pair structure then you can use ArrayList and then for sorting purpose you case use Collection of java.util.Collections to sort your arraylist Jan 20, 2015 at 11:22
  • No duplicates, HashMap and LinkedList are no good. Hashmap doesn't order anything. LinkedLists are not keyvalue pairs.
    – David
    Jan 20, 2015 at 11:49

2 Answers 2

3

If you...

  • ...need to have the elements ordered
  • ...don't want duplicates
  • ...want to be able to iterate from a specific point

you can use TreeSet.

Demo:

TreeSet<Integer> ints = new TreeSet<>(Arrays.asList(2,4,5,9,11));

System.out.println(ints.tailSet(4, false));  // [5, 9, 11]
System.out.println(ints.headSet(4, false));  // [2]

(If you want a Map you can use TreeMap with tailMap and headMap.)

2
  • The thing is, I also need direct acces. So that's why I ended up with a Map subclass.
    – David
    Jan 20, 2015 at 11:53
  • Ah, goddamnit, I didn't read your answer right. So a map can have a head and a tail as well :). You just deserved yourself the answer :)
    – David
    Jan 20, 2015 at 13:20
0

You can use a SortedSet, it's a Set that further provides a total ordering on its elements. The elements are ordered using their natural ordering or by a Comparator typically provided at sorted set creation time (doc here).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.