Why aren't Java Collections remove methods generic?

前端 未结 10 2155
旧巷少年郎
旧巷少年郎 2020-11-22 04:49

Why isn\'t Collection.remove(Object o) generic?

Seems like Collection could have boolean remove(E o);

Then, when you ac

10条回答
  •  忘了有多久
    2020-11-22 05:52

    In addition to the other answers, there is another reason why the method should accept an Object, which is predicates. Consider the following sample:

    class Person {
        public String name;
        // override equals()
    }
    class Employee extends Person {
        public String company;
        // override equals()
    }
    class Developer extends Employee {
        public int yearsOfExperience;
        // override equals()
    }
    
    class Test {
        public static void main(String[] args) {
            Collection people = new ArrayList();
            // ...
    
            // to remove the first employee with a specific name:
            people.remove(new Person(someName1));
    
            // to remove the first developer that matches some criteria:
            people.remove(new Developer(someName2, someCompany, 10));
    
            // to remove the first employee who is either
            // a developer or an employee of someCompany:
            people.remove(new Object() {
                public boolean equals(Object employee) {
                    return employee instanceof Developer
                        || ((Employee) employee).company.equals(someCompany);
            }});
        }
    }
    

    The point is that the object being passed to the remove method is responsible for defining the equals method. Building predicates becomes very simple this way.

提交回复
热议问题