0

我有如下所示的用户对象:

用户.java:

    public class User {
        public String firstName;
        public String lastName;

        public String getFirstName() {
            return firstName;
        }   
        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }
        public String getLastName() {
            return lastName;
        }
        public void setLastName(String lastName) {
            this.lastName = lastName;
        }

        @Override
        public int hashCode() {
            return (this.firstName.hashCode() + this.lastName.hashCode());
        }

        @Override
        public boolean equals(Object obj) {
            if(obj instanceof User) {
                User temp = (User) obj;
                if(this.firstName.equals(temp.firstName) && this.lastName.equals(temp.lastName)) {
                    return true;
                }
            }
            return false;
        }
    }

主程序如下图所示:

    import java.util.*; 

    class pp {
        public static void main(String[] args) {
            List<User[]> a = new ArrayList<User[]>();
            User[] u = new User[3];

            u[0] = new User();
            u[0].setFirstName("Mike"); u[0].setLastName("Jordon");      

            u[1] = new User();
            u[1].setFirstName("Jack"); u[1].setLastName("Nicolson");

            u[2] = new User();
            u[2].setFirstName("Jack"); u[2].setLastName("Nicolson");

            a.add(u);

            Set<User[]> s = new HashSet<User[]>(a);

            for (User[] ss : s) {
                for (int i=0; i<ss.length; i++) {           
                    System.out.println(ss[i].getFirstName() + " " + ss[i].getLastName());
                }
            }
        }
    }

我期望输出是

Mike Jordon
Jack Nicolson

但不知何故,它保留了重复的对象并打印为:

Mike Jordon
Jack Nicolson
Jack Nicolson

谁能告诉我我错过了什么?

谢谢!

4

9 回答 9

6

你的 equals 方法应该是这样的:

  @Override
    public boolean equals(Object obj) {
        if(obj instanceof User) {
            User temp = (User) obj;
            if(this.firstName.equals(temp.firstName) && this.lastName.equals(temp.lastName)) {
                return true;
            }
        }
        return false;
    }
于 2012-07-23T06:26:28.707 回答
5

我已经解决了您的问题并理解了要求。请找到我已经实现的类似代码,并且还成功地从集合中删除了具有重复值的对象。

@Snipet...

Employee.java
==============

package com.hcl;

public class Employee {

    public String empid;
    public String empname;
    public double sal;
    public int age;

    public Employee(){

    }

    public Employee(String empid,String empname,double sal,int age){

        this.empid = empid;
        this.empname = empname;
        this.sal = sal;
        this.age = age;
    }

    public String getEmpid() {
        return empid;
    }
    public void setEmpid(String empid) {
        this.empid = empid;
    }
    public String getEmpname() {
        return empname;
    }
    public void setEmpname(String empname) {
        this.empname = empname;
    }
    public double getSal() {
        return sal;
    }
    public void setSal(double sal) {
        this.sal = sal;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

    /**
     * This override method playes a major role to remove duplicate values
     */
    @Override
    public int hashCode() {
        return (this.empid.hashCode() + this.empname.hashCode()+String.valueOf(this.sal).hashCode()+String.valueOf(this.age).hashCode());
    }

    /**
     * This override method plays a major role to remove duplicate values
     */
    @Override
    public boolean equals(Object obj) {
        if(obj instanceof Employee) {
            Employee temp = (Employee) obj;

            if(this.empid.equals(temp.empid) && this.empname.equals(temp.empname) && String.valueOf(this.sal).equals(String.valueOf(temp.sal)) && String.valueOf(this.age).equals(String.valueOf(temp.age))) {
                return true;
            }
        }
        return false;
    }

}

@Snipet..........
RemoveDuplicateObjects.java
=============================
package com.hcl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class RemoveDuplicateObjects {


    public static void main(String[] args) {

        Employee emp1 = new Employee("1","bapi",1000,31);
        Employee emp2 = new Employee("2","mano",2000,29);
        Employee emp3 = new Employee("1","bapi",1000,31); // emp3 == emp1 duplicate object
        Employee emp4 = new Employee("3","Rohan",3000,27);
        Employee emp5 = new Employee("1","bapi",1000,31); // emp5 == emp3 == emp1 duplicate object

        RemoveDuplicateObjects obj = new RemoveDuplicateObjects();

        // empList contains objects having duplicate values. How to remove duplicate? 
        List<Employee> empList = new ArrayList<Employee>();
        empList.add(emp1);
        empList.add(emp2);
        empList.add(emp3);
        empList.add(emp4);
        empList.add(emp5);

        if(emp1.equals(emp2)){

            System.out.println("emp1 and emp2 are equal");
        }

        if(emp1.equals(emp3)){
            System.out.println("emp1 and emp3 are equal");
        }
        obj.removeDuplicate(empList);

    }

    // method is used for removing objects having duplicate values
    private void removeDuplicate(List<Employee> empList) {


        Set<Employee> empSet = new HashSet<Employee>();
        empSet.addAll(empList);

        for(Employee e: empSet){

            System.out.println("id = "+e.getEmpid());
            System.out.println("name = "+e.getEmpname());
            System.out.println("sal = "+e.getSal());
            System.out.println("age = "+e.getAge());
        }

    }

}

Done! Now you can run the program and analyze the solution.
于 2013-01-13T09:34:44.767 回答
1

我想你想要这个:

 class pp {
        public static void main(String[] args) {
            Set<User> a = new HashSet<User>();

        User u = new User();
        u.setFirstName("Mike"); u.setLastName("Jordon");  
        a.add(u);

        u = new User();
        u.setFirstName("Jack"); u.setLastName("Nicolson");
        a.add(u);

        u = new User();
        u.setFirstName("Jack"); u.setLastName("Nicolson");

        a.add(u);

        for (User ss : a) {           
                System.out.println(ss.getFirstName() + " " + ss.getLastName());
        }
    }
}
于 2012-07-23T06:29:28.750 回答
1

试试这个我的朋友:

        Iterator i = a.iterator();
        while (i.hasNext()) {
            User u = (User) i.next();
            boolean match = false;
            Iterator j = a.iterator();
            boolean once = true;
            while (j.hasNext()) {                    
                if(once){j.next();} // to skip own occurence only once
                once = false;                    
                User u2 = (User) j.next();
                if (u.getFirstName().equals(u2.getFirstName())
                        && u.getLastName().equals(u2.getLastName())) {
                    match = true;
                }
            }
            if (!match) {
                // print
            }
        }
于 2012-07-23T06:44:01.990 回答
0

通常,您可以将元素添加到 aSet以删除重复项。但是,您通常不想将整个数组添加到集合中;您只想添加单个元素,如下所示:

    public static void main(String[] args) {
        Set<User> a = new HashSet<User>();
        User[] u = new User[3];

        u[0] = new User();
        u[0].setFirstName("Mike"); u[0].setLastName("Jordon");      

        u[1] = new User();
        u[1].setFirstName("Jack"); u[1].setLastName("Nicolson");

        u[2] = new User();
        u[2].setFirstName("Jack"); u[2].setLastName("Nicolson");

        // Add each of the users to the Set.  Note that there are three.
        for (User user : u) {
            a.add(u);
        }

        // Get the results back as an array.  Note that this will have two.
        User[] duplicatesRemoved = new User[0];
        a.toArray(duplicatesRemoved);
    }
于 2012-07-23T06:29:28.457 回答
0

按照 Jason 的建议覆盖 equals 方法。现在要删除重复项,您需要使用 Set。

List 允许重复值,因此您将始终有重复值。Set 不允许重复值,因此它将解决您的问题。

于 2012-07-23T06:31:27.350 回答
0

您正在使用一组数组,其中该组有一个元素,即三个用户的数组。数组不强制或检查唯一性,这就是为什么您两次获得相同的用户。如果您完全删除了这些数组,并且只使用了一个 Set,您将获得您想要的“独特”行为。

于 2012-07-23T06:33:10.827 回答
0

首先,如果您不想重复,您应该使用 Set 来存储对象而不是数组。(数组和列表确实允许存储重复的对象)

其次,您的 equals 方法应使用 String.equal 方法进行比较,并且也应检查空值以确保安全。我会始终使用 IDE 的自动生成功能来处理 hashcode 和 equals 方法(即 Eclipse Source -> Generate hashCode() and equals()...)

 @Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
    result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    User other = (User) obj;
    if (firstName == null) {
        if (other.firstName != null)
            return false;
    } else if (!firstName.equals(other.firstName))
        return false;
    if (lastName == null) {
        if (other.lastName != null)
            return false;
    } else if (!lastName.equals(other.lastName))
        return false;
    return true;
}

和主要方法

public static void main(String[] args) {
    List<Set<User>> a = new ArrayList<Set<User>>();
    Set<User> set = new HashSet<User>();

    User u = new User();
    u.setFirstName("Mike"); u.setLastName("Jordon");      
    set.add(u);

    u = new User();
    u.setFirstName("Jack"); u.setLastName("Nicolson");
    set.add(u);

    u = new User();
    u.setFirstName("Jack"); u.setLastName("Nicolson");
    set.add(u);

    a.add(set);

    for (Set<User> ss : a) {
        for (User user : ss) {           
            System.out.println(user.getFirstName() + " " + user.getLastName());
        }
    }
}
于 2012-07-23T06:41:24.200 回答
0

您好,您可以在 pp 类中编写一个方法,以便从用户数组中删除重复元素,如下所示:

private User[] getUserArrayWithoutDuplicates(User[] a) {
    int count = a.length;
    Set<User> tempset = new HashSet<User>();
    for (int i = 0; i < count; i++) {
        User[] user = a;
        int arraysize = user.length;
        for (int j = 0; j < arraysize; j++)
            tempset.add(user[j]);
    }
    User[] usr = new User[tempset.size()];
    Iterator<User> tempIterator = tempset.iterator();
    int p = 0;
    while (tempIterator.hasNext()) {
        User user = tempIterator.next();
        usr[p] = new User();
        usr[p].setFirstName(user.firstName);
        usr[p].setLastName(user.lastName);
        p++;
    }
    return usr;
}

此方法将从用户数组中删除重复条目并返回没有重复条目的用户数组。

于 2012-07-23T07:41:10.933 回答