IzonFreak
IzonFreak

Reputation: 409

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

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.

Upvotes: 0

Views: 221

Answers (5)

vrbsm
vrbsm

Reputation: 1218

R class modifies the value ID.

I suggest you use the Tag attribute.

Upvotes: 0

Chamatake-san
Chamatake-san

Reputation: 551

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

Upvotes: 1

Tragalunas
Tragalunas

Reputation: 311

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?

Upvotes: 1

S.Thiongane
S.Thiongane

Reputation: 6905

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");

Upvotes: 0

mjuopperi
mjuopperi

Reputation: 972

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.

Upvotes: 1

Related Questions