简体   繁体   English

Java我如何给数组中的元素一个唯一的ID

[英]Java how do I give elements in an array a Unique ID

I'm new to programming and I've got a task to make a swing/GUI crud where you are able to put in people/animal/movies into an array etc (I'm currently doing people) and it will generate mail, username etc. I've done all that but I'm missing one thing. 我是编程新手,我有个任务要制作一个swing / GUI组件,您可以在其中将人/动物/电影放入数组等(我目前在做人),它将生成邮件,用户名等。我已经完成了所有操作,但是我缺少一件事。

Now - I want to give each element in the array an unique ID of some sort where if 1 person has ID 25 for instance, so there can't be another element with the same ID 25 unless i remove that specific element. 现在-我想为数组中的每个元素赋予某种唯一的ID,例如,如果一个人的ID为25,那么除非我删除该特定元素,否则不可能有另一个具有相同ID 25的元素。

I use a Jframe and then a java public class where i have get's and set's for my Jframe. 我使用一个Jframe,然后使用一个Java公共类,其中有我的Jframe的get和set的。

Sorry but I'm new - thank you. 抱歉,我是新手-谢谢。

Java.lang.Object has methods called hasCode() and equals() . Java.lang.Object具有称为hasCode()equals() These methods play a significant role in the real time application. 这些方法在实时应用中起着重要作用。 However its use is not always common to all applications. 但是,并非所有应用程序都使用它。

hashCode() hashCode()

As you know this method provides the has code of an object. 如您所知,此方法提供了对象的has代码。 Basically the default implementation of hashCode() provided by Object is derived by mapping the memory address to an integer value. 基本上, Object提供的hashCode()的默认实现是通过将内存地址映射到整数值来派生的。 If look into the source of Object class , you will find the following code for the hashCode . 如果查看Object类的源代码,您将找到以下用于hashCode代码。 public native int hashCode() ; public native int hashCode() ; It indicates that hashCode is the native implementation which provides the memory address to a certain extent . 这表明hashCode是本机实现,可以在一定程度上提供内存地址 However it is possible to override the hashCode method in your implementation class. 但是,可以在实现类中覆盖hashCode方法。

equals() 等于()

This particular method is used to make equal comparison between two objects. 此特定方法用于在两个对象之间进行相等比较。 There are two types of comparisons in Java . Java有两种类型的比较。 One is using “= =” operator and another is “equals()” . 一种使用“= =”运算符,另一种使用“equals()” I hope that you know the difference between this two. 我希望您知道这两者之间的区别。 More specifically the “.equals()” refers to equivalence relations. 更具体地说, “.equals()”是指等价关系。 So in broad sense you say that two objects are equivalent they satisfy the “equals()” condition. 因此,从广义上讲,您说两个对象相等,它们满足“equals()”条件。 If you look into the source code of Object class you will find the following code for the equals() method. 如果查看Object类的源代码,您将找到equals()方法的以下代码。

So, lets create a class Person overriding these methods: 因此,让我们创建一个重写以下方法的Person类:

public class Person {

    private Integer personId;
    private String fullName;

    public Integer getPersonId() {
        return personId;
    }

    public void setPersonId(Integer personId) {
        this.personId = personId;
    }

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    @Override
    public String toString() {
        return "Person [personId=" + personId + ", fullName=" 
                        + fullName + "]";
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((fullName == null) ? 0 : fullName.hashCode());
        result = prime * result + ((personId == null) ? 0 : personId.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;
        Person other = (Person) obj;
        if (fullName == null) {
            if (other.fullName != null)
                return false;
        } else if (!fullName.equals(other.fullName))
            return false;
        if (personId == null) {
            if (other.personId != null)
                return false;
        } else if (!personId.equals(other.personId))
            return false;
        return true;
    }

}

and now our main class to create and manage duplicate objects of class Person: 现在是我们的主类,用于创建和管理Person类的重复对象:

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class UniqueArrayExample {

    //To remove duplicates objects we use here HashSet util collection
    private static Set<Person> personSet = new HashSet<Person>();

    public static void main(String[] args) {

        //creating four objects of Person Class
        Person person1 = new Person();
        Person person2 = new Person();
        Person person3Dupl = new Person();
        Person person4 = new Person();

        //third object person3Dup1 is duplicate of Object person1
        person1.setPersonId(12341);
        person2.setPersonId(12342);
        person3Dupl.setPersonId(12341);
        person4.setPersonId(12344);

        person1.setFullName("Suresh Kumar");
        person2.setFullName("Mahesh Singh");
        person3Dupl.setFullName("Suresh Kumar");
        person4.setFullName("Rajkumar Singh");

        //Add those Person class Object to Set<Person> collection
        personSet.add(person1);
        personSet.add(person2);
        personSet.add(person3Dupl);
        personSet.add(person4);

        //So here after getting all Objects to Iterator and by 
        //printing those will not give you the person1 Object duplicate.
        Iterator<Person> iterator = personSet.iterator();
        while(iterator.hasNext()) {
            System.out.println(iterator.next().toString());
        }
    }

}

here output generated as above class: 这里输出生成为上面的类:

Person [personId=12342, fullName=Mahesh Singh]
Person [personId=12341, fullName=Suresh Kumar]
Person [personId=12344, fullName=Rajkumar Singh]

the duplicate object possibles to remove by use of HashSet , because of overriding hashCode() and equals() methods inside class Person , if you remove those methods from the class Person , Set collection will add all Objects of Person and will remove the redundancy. 由于覆盖了Person类中的hashCode()equals()方法,因此可以使用HashSet删除重复的对象,如果从Person类中删除这些方法,则Set集合将添加Person所有Objects并删除冗余。

Hope this would help you. 希望这对您有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM