java 如何确定 Student 类的两个实例是否代表同一个学生?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5055559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I determine whether two instances of a Student class represent the same student?
提问by kgrad
I have a Java class
我有一个 Java 类
class Student
{
String name;
int age;
}
Also, I have two instances of the Student class student1
and student2
.
另外,我有两个 Student 类student1
和student2
.
One way to find out whether both the instances represent the "same student" is to compare the data manually, i.e., the name and age. If they are the same, then they represent the "same student".
找出两个实例是否代表“同一学生”的一种方法是手动比较数据,即姓名和年龄。如果它们相同,则它们代表“同一个学生”。
Is there any other way to find out whether the two instances represent the "same student"?
有没有其他方法可以找出两个实例是否代表“同一个学生”?
P.S. I was asked this question in an interview. I still do not fully understand the phrase "same student". I am guessing it means same student in the real world. If not, what else could the interviewer have meant?
PS 我在面试中被问到这个问题。我仍然不完全理解“同一学生”这句话。我猜这意味着现实世界中的同一个学生。如果不是,那么面试官还有什么意思?
回答by corsiKa
What identifies the student?
学生的身份是什么?
We don't have anything but a name and an age. Now, you COULD have two people of the same name, but probably not. In any event, I wouldn't consider age to be something that identifies someone - not like a name does.
除了名字和年龄,我们一无所有。现在,你可以有两个同名的人,但可能不是。无论如何,我不会认为年龄是识别某人的东西——不像名字那样。
So I would do this
所以我会这样做
public boolean equals(Object o) {
if(!o instanceof Student) return false;
Student s = (Student)o;
return o.name.equals(this.name);
}
In case you're new to Java, the Object class has a method public boolean equals(Object o)
. Because EVERY object in Java inherits from Object, they ALL have that method, whether they want it or not. The default implementation simply compares the address in memory. So if you were to do
如果您是 Java 新手,Object 类有一个方法public boolean equals(Object o)
。因为 Java 中的每个对象都继承自 Object,所以它们都具有该方法,无论是否需要。默认实现只是比较内存中的地址。所以如果你要这样做
Student s = new Student();
Student t = new Student();
boolean e = (s == t); // always false
boolean q = s.equals(t); // always false if not overridden
Now, this particular method that I wrote doesn't do null checks, which you would want to do if it were in production code.
现在,我编写的这个特定方法不执行空检查,如果它在生产代码中,您会想要这样做。
回答by kgrad
There are two definitions of the same student in Java (if student is an object). There is the case where the student has the same name and age which can be checked by implementing the .equals() method. This means that their values are equal.
Java中同一个student有两个定义(如果student是一个对象)。存在学生具有相同姓名和年龄的情况,可以通过实施 .equals() 方法进行检查。这意味着它们的值相等。
@Override
public boolean equals(Object o) {
//check if the student's age and name are equal
}
The second case refers to when two different variables point to the same actual object, this is known as referential equality and can be tested with ==.
第二种情况是指当两个不同的变量指向同一个实际对象时,这称为引用相等性,可以用 == 进行测试。
if (student1 == student2)
回答by 2sb
Really good question, Trying my best and hope it will make you understand...
真的很好的问题,尽我所能,希望它能让你明白......
First copying your text Your text = "One way to find out whether both the instances represent the "same student" is to compare the data manually, i.e., the name and age. If they are the same, then they represent the "same student." and "I am guessing it means same student in the real world."
首先复制你的文本 Your text = "判断两个实例是否代表“同一个学生”的一种方法是手动比较数据,即姓名和年龄。如果它们相同,那么它们代表“同一个学生” .”和“我猜这意味着现实世界中的同一个学生。”
Your first stmt is wrong whereas your guess is right. In a school there are two students of name Frank and both Frank have same age. Does that means that they are same. No off course not. Even if you compare say 5 datas and it could be possible that those 5 data of two different student matches. In real world it is very easy to look at them and say that they are different.
您的第一个 stmt 是错误的,而您的猜测是正确的。在一所学校里,有两个名字叫 Frank 的学生,并且两个 Frank 的年龄相同。这是否意味着它们是相同的。没有当然没有。即使您比较说 5 个数据,也有可能两个不同学生的这 5 个数据匹配。在现实世界中,很容易看到它们并说它们不同。
In the language of java "==" double equals refers to "same" and is called the same instance.
在 Java 语言中,“==”双等于指的是“相同”,称为相同实例。
If two reference variable student1 and student2 referes to the same instance this means that they are referring to the same student or in the language of java "same instance of student"
如果两个引用变量 student1 和 student2 指的是同一个实例,这意味着它们指的是同一个学生或在 java 语言“same instance of student”中
In the context of student == is important and suggest you to read .equals() method to understad more about equality.
在学生 == 的上下文中很重要,建议您阅读 .equals() 方法以了解更多关于平等的信息。
回答by Ethan Manzi
In my opinion, the easiest way to implement this is to do what most people has said. You can use the inherited method equals
from the Object class ( which all classes inherit from ). If this is for a larger project, I'd also recommend doing something like this:
在我看来,实现这一点最简单的方法就是按照大多数人所说的去做。您可以使用equals
Object 类(所有类都继承自)的继承方法。如果这是针对更大的项目,我还建议您执行以下操作:
Assign a UUID to each and every Student
object. This gives every student a uniquely identifiable ID, then you can easily compare those two values in the equals
method. To automatically have it generate a UUID, you can generate a string, based on the hash of all of the attributes, plus some pysudo-random attribute, things like the current time should work. This would prevent overlaps in cases even where two students have the exact same information, because they can't be generated at the exact same time, they'll always have a different UUID.
为每个Student
对象分配一个 UUID 。这为每个学生提供了一个唯一可识别的 ID,然后您可以轻松地比较方法中的这两个值equals
。为了让它自动生成一个 UUID,你可以生成一个字符串,基于所有属性的哈希值,加上一些 pysudo-random 属性,像当前时间这样的东西应该可以工作。即使在两个学生拥有完全相同的信息的情况下,这也可以防止重叠,因为它们不能在完全相同的时间生成,他们将始终具有不同的 UUID。
You could then create a container class, using a HashMap<String, Student>
to store all students, and create method getStudentByID(String id)
and setStudentByID(String id, Student value)
to easily access and manage all students within your collection.
然后您可以创建一个容器类,使用 aHashMap<String, Student>
来存储所有学生,并创建方法getStudentByID(String id)
并setStudentByID(String id, Student value)
轻松访问和管理您集合中的所有学生。
That's how I'd do it, anyways.
反正我就是这样做的。
If you want to solve it without implementing extra thingsyou could use this snippet below.
如果你想在不实施额外的事情的情况下解决它,你可以使用下面的这个片段。
package Snippet1;
public class Snippet1 {
static class Student {
public String name;
public int age;
@Override
public boolean equals(Object obj) {
if (obj.getClass().isAssignableFrom(Student.class)) {
Student secondStudent = (Student) obj;
if (secondStudent.age == this.age && secondStudent.name.equalsIgnoreCase(this.name)) {
// Student, with all the same information
return true;
} else {
// Student, but with different information
return false;
}
} else {
// Not a student!
return false;
}
}
}
public static void main(String[] args) {
// Your example ( with little changes )
Student student1 = new Student();
student1.name = "Jane";
student1.age = 15;
Student student2 = new Student();
student1.name = "John";
student2.age = 17;
if (student1.equals(student2)) {
System.out.println("Same student!");
} else {
System.out.println("Different student!");
}
}
}
}