javaandroidarraylistexists

Checking if arraylist object exists


Well, my question is this.

My class Message contains:

My class User contains:

**This is how I add info to my arrayList:

User user = new User();
    user.setId(1);
    user.setName("stackover");
    Message msg = new Message();
    msg.setid(10);
    msg.setmessage("hi");
    msg.setUser(user);
    arrayList.add(msg)

http://pastebin.com/99ZhFASm**

I have an arrayList<Comment> which contains id, message, User.

I want to know if my arrayList<Comment> already contains the id of "user"

Note: already tried with arraylist.contains

(Android)


Solution

  • Since you have object Message which has unique identifier (id), don't place it in ArrayList, use HashMap or HashSet. But first, you need to create methods equal() and hashCode() in that object:

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
    
        Message message = (Message) o;
    
        return id == message.id;
    
    }
    
    @Override
    public int hashCode() {
        return id;
    }
    

    in this way, you can use advantages of map and set. So, do this:

    User user = new User();
    user.setId(1);
    user.setName("stackover");
    
    Message msg = new Message();
    msg.setid(10);
    msg.setmessage("hi");
    msg.setUser(user);
    
    HashMap<Integer, Message> map = new HashMap<>();                 
    map.add(new Integer(msg.getId()), msg);
    
    boolean isItInMapById = map.containsKey(new Integer(10));
    boolean isItInMapByObject = map.containsValue(msg);
    

    If you need ArrayList of Messages, just do this:

    ArrayList<Message> messages = new ArrayList<>(map.values());
    

    You can also get list of ids if you need it:

    List<Set<Integer>> idList = Arrays.asList(map.keySet());