Arraylist custom location

I have an arraylist and I want to update a specific element. I am adding data to a list with this line:

randomsList.add(new Random(result.get(i).getAsJsonObject(),0));


This adds data to the 0,1,2,3,4 ... locations, so when I try to update the item, I don't know where the object is.

I am updating the data with this line:

randomsList.set(position,new Random(user,1));


I think if I use custom numbers for the location I can update a specific item. My prototype:

randomsList.add({USER_ID},new Random(result.get(i).getAsJsonObject(),0));


And if I want to update it, I use this line:

randomsList.set({USER_ID},new Random(user,1));


Is this a good approach? If your answer is no, how should it be?

PS : I am using this arraylist with an adapter


source to share

1 answer

As @itachiuchiha mentions, you must use a map. The "custom numbers" you mentioned is your key (integers) and the value is an object Random


As an aside, in response to your comment, there is an Android example below Adapter

that uses a map as its underlying data source.

public class RandomsAdapter extends BaseAdapter {

    private Map<Integer, Random> randoms;

    public RandomsAdapter(Map<Integer, Random> randoms) {
        this.randoms = randoms;

    public void updateRandoms(Map<Integer, Random> randoms) {
        this.randoms = randoms;

    public int getCount() {
        return randoms.size();

    public Random getItem(int position) {
        return randoms.get(position);

    public long getItemId(int position) {
        // we won't support stable IDs for this example
        return 0;

    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            view = createNewView();
        update(view, songs.get(position));
        return view;

    private View createNewView() {
        // TODO: create a new instance of your view and return it
        return null;

    private void update(View view, Random random) {
        // TODO: update the rest of the view



Pay attention to the method updateRandoms(Map<Integer, Random> randoms)


As long as you can expose a method in the adapter to update one record in the Map, the Adapter should not handle map changes. I prefer to pass the entire map over again - it can still be a reference to the same object, but the adapter doesn't know or care; it just knows "my underlying datasource has been modified / changed, I need to tell my observers to update their views by calling notifyDataSetChanged()


Alternatively, you can call notifyDataSetChanged()

on the adapter externally when you change the basemap (this tells the ListView that its data is out of date and requests its views from the adapter again).



All Articles