-1
private Map<Group, List<Contact>> groupedContactList = 
    new HashMap<Group, List<Contact>>();

I'm trying to implement a getGroup(int position) method but I'm having trouble.

I've tried (Group)groupedContactList.keySet().toArray()[position]; but its not working.

EDIT: the getGroup() method must be overriden because I am extending an adapter so I cant change the method signature unfortunately.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Ogen
  • 6,499
  • 7
  • 58
  • 124

2 Answers2

2

A Map object lends itself well to using a key rather than a position value to get what you're looking for.

Map objects store information in key/value pairs. In your example, the key is a Group and the value is a List of Contacts. In order for it all to work, your key object must implement the equals(Object object) method.

public class Group { 
    //lots of really great code that defines a Group
    public boolean equals(Object obj) {
        if( Object == null ) return false; 
        if( !(Object instanceof Group) ) return false; 
        if( this == obj ) return true; 

        Group compareMe = (Group)obj; 
        if( this.getId() != null && compareMe.getId() != null && this.getId().equals(compareMe.getId()) ) return true; 
        return false; 
    }
}

Then the map.get(Group key) can be used to get what you are looking for.

The real issue is that Maps are not sorted collections. There is no guaranteed order to the way the information is stored there, so you can't really be guaranteed that getting something based on position value 1 will be the same every time.

  • 3
    To be precise, HashMaps aren't sorted. Maps (the interface) may have implementations that guarantee iteration order. – Dave Newton Oct 17 '13 at 01:34
  • 1
    A good answer that provides some alternatives: http://stackoverflow.com/questions/2817695/how-does-java-order-items-in-a-hashmap-or-a-hashtable – Jeroen Vannevel Oct 17 '13 at 01:36
0

If you use a LinkedHashMap, which preserves the order in whick the key/value pairs were added, I think your code should work. Give it a try.

user949300
  • 15,364
  • 7
  • 35
  • 66