user2135196
user2135196

Reputation: 21

Getting indexof arraylist of class. java

I have class listA:

public class lista {
            int i;
            String name;

            public lista(int i, String name)
            {
                this.i = i;
                this.name = name;
            }
    }

I made ArrayList from this class.

 public static ArrayList<lista> friends;

Adding some date: 14 - Adam 2 - John 35 - Arnold 74 - x 54 - x

and i want to get IndexOf 74 and change name from x to Catrina.

How to do it?

friends.get(friends.indexOf(??)) = "catarina";

Upvotes: 0

Views: 202

Answers (2)

ppeterka
ppeterka

Reputation: 20726

This is not how it works. The i in your class lista is not the index of where it is in the list.

First of all, you have to change your class. This is not nice coding.

public class Friend { 
       //note1: Class Names Start With Capital Letter!
       //note2: Class names have meaning!

        private int i; //notice private modifier. 
        private String name; //notice private modifier.

        public Friend (int i, String name)
        {
            this.i = i;
            this.name = name;
        }
        /* getter and setter methods */
        public int getI() {
            return i;
        }
        public String getName()
            return name;
        }
        public void setName(String name)
            this.name = name;
        }
      /* don't forget equals() and hashCode() */

}

Of course, a proper equals() and hashCode() method is crucial to be able to workwith them properly - but there is an abundance of materials regarding this subject on the net...

Given that class, you have to traverse the list to find the elements:

for(Friend friend: friends) {
    if(&& friend.getI()==74) {
        friend.setName("Cristina");
    }
}

But from here, there are still some improvements to make. The approach of cowls is in the right direction, but I'd take it one step further, by using a Map<Integer, Friend>:

//create Map
Map<Intger, Friend> friends = new HashMap<Integer, Friend>();
//note: use interface for declaring variables where possible to hide implementation specifics!

//add friends:
friends.put(75, new Friend(75,"a")); 
//... left ot others for brevity

//modify part:
Friend f = friends.get(75);
if(f!=null) { //always check for null
   f.setName("Christina");
}

What more do you get compared to cowls' approach? If you want to add fields to the Friend class - you are free to do that without pain of having to deal with converting everything...

Upvotes: 0

cowls
cowls

Reputation: 24334

It looks like you would be better of using a Map as they are much better equipped to handle key value pairs which is what you have here.

Map<Integer, String> friends = new HashMap<Integer, String>();

friends.put(14, "Adam");

friends.get(14); //Adam

friends.put(14, "John");

friends.get(14); //Now John

Upvotes: 5

Related Questions