Best way to implement a uniqueID for an Object in Java/Android in an ArrayList

时间:2015-05-24 20:57:46

标签: java android

So i have an Android project with an ArrayList of objects, the information in each object is display using an ArrayAdapter, I remove and add new objects constantly and I want to be able to identity each object quickly with out the need to use the index number (ArrayList) or the values inside the object. What will be a good way to do this ? memory address perhaps? right now my code is depending on the Index number for a number of functions but i prefer not to do it this way because it might change (by deleting an object) and generate the display of bad information.

This ID's should change every time I initialize the app ? or should they be permanent ?

Any ideas will be appreciate.

5 个答案:

答案 0 :(得分:1)

You could use UUID's as unique keys in a Map. It sounds like you want to access the items by a key, so an ArrayList is perhaps not the best collection for that.

答案 1 :(得分:1)

Don't you have a primary key for the objects you are handling in your data model? You could access the list view items through their id, via setTag()/getTag() of the item.

Setting tags to each item in a ListView in Android?

答案 2 :(得分:1)

Another option is to use java's atomicInteger to assign IDs to your objects as a field in that class and store that ID in a map like the other person suggested. AtomicInteger is thread safe and should remain unique in any given user session with your app. If you need more numbers, I believe there is also an AtomicLong.

Either way, it sounds like you need to use a Map or HashMap if you need to have quick access to these objects. HashMaps are indexed so you won't have to waste processing resources looping through lists all the time.

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicInteger.html

答案 3 :(得分:0)

You can try to use HashMaps. Instead of numbers/indexes to access your objects/functions, you can defined String keys, and simply access your objects/functions.

An example:

 HashMap<String, String> meMap=new HashMap<String, String>();
 meMap.put("first","String 1");
 meMap.put("second","String 2");

Then get "String 1" using : meMap.get("first");

答案 4 :(得分:0)

R class修改值ID。

我建议你使用Tag属性。