Remove object from ArrayList with some Object property

后端 未结 5 674
轻奢々
轻奢々 2020-12-06 12:06

I am maintaining one ArrayList of objects. And my object structure is Id, name, some other details. I need to remove one the object with some id value say(10) a

5条回答
  •  Happy的楠姐
    2020-12-06 13:01

    Maybe I don't understand the question but why nobody suggested to use override equals and hashcode for that user class?

    class MyObject {
        final String id;
        final String name;
    
        MyObject(String id, String name) {
            this.id = id;
            this.name = name;
        }
    
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            return Objects.equals(id, ((MyObject) o).id);
        }
    
        @Override
        public int hashCode() {
            return id != null ? id.hashCode() : 0;
        }
    
        @Override
        public String toString() {
            return "MyObject{id='" + id + "', name='" + name + "'}";
        }
    }
    

    in this case you can easy remove any object from list

            final ArrayList list = new ArrayList<>();
            list.add(new MyObject("id1", "name1"));
            list.add(new MyObject("id2", "name2"));
            list.add(new MyObject("id3", "name3"));
    
            MyObject removeCandidate = new MyObject("id2", "name2");
    
            list.remove(removeCandidate);
            System.out.println(list);
    

    code above prints

    [MyObject{id='id1', name='name1'}, MyObject{id='id3', name='name3'}]
    

提交回复
热议问题