How to create unique identifiers for RecyclerView, in case of 2 identifiers per element?

Background

Suppose I have a RecyclerView that has elements that can only be unique if you look at the 2 identifiers that they have, but not just one of them.

The first identifier is the first. Usually there are no two elements having the same primary identifier, but sometimes this can happen, so there is a secondary identifier.

In my

Problem

The RecyclerView adapter must be returned with a "long" type:

https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#getItemId(int)

What i tried

An easy way to overcome this is to have a HashMap and a counter.

HashMap , , . . "".

, RecyclerView 2 :

HashMap<Pair<Long,Long>,Long> keyToIdMap=new HashMap();
long idGenerator=0;

getItemId:

Pair<Long,Long> combinedKey=new Pair(item.getPrimaryId(), item.getSecondary());
Long uniqueId=keyToIdMap.get(combinedKey);
if(uniqueId==null) 
  keyToIdMap.put(combinedKey,uniqueId=idGenerator++);
return uniqueId;

. , , , , ...

, , ( - Pair).

, , 0.

, ?

, ? , . -?

+6
2

, - , . ids, .

0

64- ? , 64- , , .

- (, , SHA2) 64 . 64 , , - 50% sqrt (64) = 2 ** 32 , 4 .

, , , ( , ..). Java , Longs , , -.

SHA1:

Guava - .

HashFunction hf = Hashing.sha1();
long hashedId = hf.newHasher()
       .putLong(primary)
       .putLong(secondary)
       .hash()
       .asLong();

JDK, , , , ( ):

static void updateDigestWithLong(MessageDigest md, long l) {
  md.update((byte)l);
  md.update((byte)(l >> 8));
  md.update((byte)(l >> 16));
  md.update((byte)(l >> 24));
}

// this is from the Guava sources, can reimplement if you prefer
static long padToLong(bytes[] bytes) {
  long retVal = (bytes[0] & 0xFF);
  for (int i = 1; i < Math.min(bytes.length, 8); i++) {
    retVal |= (bytes[i] & 0xFFL) << (i * 8);
  }
  return retVal;
}

static long hashLongsToLong(long primary, long secondary) {
  MessageDigest md = MessageDigest.getInstance("SHA-1");
  updateDigestWithLong(md, primary);
  updateDigestWithLong(md, secondary);
  return padToLong(md.digest());
}
0

All Articles