English 中文(简体)
采用java Collection<E>.contains(Object o)在推翻平等方法时
原标题:Using java Collection<E>.contains(Object o) when overriding equals method
  • 时间:2011-10-11 16:17:18
  •  标签:
  • java
  • list

我有一份清单和编号;Person>人定义相似的物体

public Person {
    private firstName;
    private lastName;
    //getter and setter methods
    public boolean equals(Object obj) {
        return lastName.equals(obj.toString());
    }
}

现在,我想看一下这份清单是否含有某种最后名称。

if(myList.contains("Smith"))
    System.out.println("yay!");

然而,如果(o=null )包含的方法是肯定的。 e=null :o. Equals(e) 因此,它正在使用Sting. Equals(Person)而不是人。 是否有解决这一问题的简单办法,或者我是否必须写明我自己的逻辑,以便载入?

最佳回答
问题回答

一种办法是利用现有手法构筑<代码>List<String>观点,并向前迈进。

final List<Person> myList = yourList;
List<String> strView = new AbstractList<String>() { 
                    String get(int i) {
                             return myList.get(i).getLastName(); 
                       } 
                     int size() { return myList.size(); }
                  };

if(strView.contains("Smith")) System.out.println("Yaay");

为此,你必须写一下自己的逻辑。

我强烈建议,在你推翻平等方法时,你坚持“java目标# Equals”定义的APIC。 许多地方都使用了平等的方法(用不同的逻辑来标出一),以后,你会陷入许多麻烦。

由于您不再寻找<代码>Person,因此,最具有共性的解决办法是,采用一种方法,具体表明其寻找最后的名称,例如contains LastName<<>>,或以任何形式,或以Person <<>>>/code>为例,并将其用作类似标准的对象。

这里的另一个选择是使用Guava s Iterables.any

 Predicate<Person> findMe(final String name){
    return new Predicate<Person>(){
        public boolean apply(Person input){
            return input.lastname.equals(name);
        }
    }
 }

 boolean contains = Iterables.any(myList, findMe("Smith"));

Function<Person, String> lastName = new Function<Person, String>(){
     public String apply(Person input){
        return input.lastName;
     }
}

boolean contains = Lists.transform(myList, lastName).contains("Smith");




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...