Mahdi
Mahdi

Reputation: 6389

Java : Compare same objects that they have same properties but do not points a same point in memory

I have an custom adapter like this:

private List<User> items = new ArrayList<>();
private Context context;
public UserSpinnerAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull
        List<User> objects) {
    super(context, resource, objects);

    this.items = objects;
    this.context = context;
}

when I want to find a position of object User that get from web api, the result of public int getPosition(@Nullable User item) is always -1. I think this is beacaus of my item that passed to the adapter is not just same as adapter user list inside although every thing is same but points to another point of memory.

So how I can compare two objects that have same properties but actualy seprated?

Upvotes: 0

Views: 74

Answers (2)

hluhovskyi
hluhovskyi

Reputation: 10106

You should override equals/hashCode methods for the object that you compare. You can do it easily by pressing Alt+Insert inside your class and choose equals() and hashCode(). If your class has another fields which are custom type, for example

public class User {
     ...
     private Location location;
     ...
}

you have to implement equals/hashCode also for Location

Upvotes: 1

epoch
epoch

Reputation: 16595

you should implement a equals/hashCode for the User object

Upvotes: 3

Related Questions