Nebo
Nebo

Reputation: 11

Java ArrayList with object in a loop

How do I know the name of the object in the ArrayList when it is declared in a loop? I can get it by an index but I don't know the name of it to locate/know if it is in the ArrayList.

import java.util.ArrayList;

public class Teste {

    public static void main(String[] args) {
        ArrayList<UserClasss> userList = new ArrayList<UserClasss>();

        for (int i = 0; i < 5; i++) {
            UserClasss user = new UserClasss();
            user.setName("name"+i);
            user.setAge((int)(Math.random()*80));
            userList.add(user);
        }
        for (UserClasss forUser:userList){
            System.out.println(forUser.getName());
            System.out.println(forUser.getAge());
        }


        //how can i know if contains it here?
        //userList.contains(user);
        //and how do i know the index of it?
        //userList.indexOf(user);


    }
}

class UserClasss {

    private String name;
    private int age;

    public void setName(String s){
        name = s;
    }
    public String getName(){
        return name;
    }
    public void setAge(int i){
        age = i;
    }
    public int getAge(){
        return age;
    }
}

Upvotes: 1

Views: 3053

Answers (2)

Frank
Frank

Reputation: 15631

To find your user class inside the List you must override the equals and hash code methods in the class UserClasss.

By doing that the contains() and indexOf() methods will be able to find them inside the Collection.

P.S. eclipse and some other IDE's can generate these methods for you.

code to add (generate by eclipse):

@Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        UserClasss other = (UserClasss) obj;
        if (age != other.age)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }

Upvotes: 7

Chuidiang
Chuidiang

Reputation: 1055

You can use contains() and indexOf(), but your UserClass should have an equals() method

public boolean equals(Object obj) 

that returns true if obj is equals to itself. In your case, you should compare the name.

public boolean equals(Object obj) {
   if (! (obj instanceof UserClass) {
      return false;
   }
   return this.name.equals((UserClass)obj).name );
}

Of course, you can compare all the attributes you wanted.

Upvotes: 1

Related Questions