簡體   English   中英

如何更改Student類,以便當s1 = new Student()和s2 = new Student()時,s1 == s2返回true?

[英]How to change Student class so that s1 == s2 return true when s1 = new Student() and s2 = new Student()?

在我的一次采訪中,一位采訪者問我:

給定一個Student類和兩個對象s1s2

s1 = new Student();
s2 = new Student();

s1 == s2將如何返回true

我告訴他讓Student課程成為一個單身人士,但他說不,並且我們必須在課程級別進行更改,以便s1 == s2將返回true

注意:我們需要更改Student類。 請不要回復s1=s2 任何線索?

運算符==檢查兩個對象是否相同。 您創建了兩個不同的equals對象。 所以它們不一樣, s1 == s2將返回false。 您必須重新定義方法equals並使用此方法檢查它們,如下所示:

s1.equals(s2)

該方法equals

指示某個其他對象是否“等於”此對象。

請注意,當您重新定義方法equals時,您還需要重新定義方法hashCode,如在equals方法的描述中明確記錄的那樣:

請注意,通常需要在重寫此方法時覆蓋hashCode方法,以便維護hashCode方法的常規協定,該方法聲明相等的對象必須具有相等的哈希代碼。

通常ide(如IntelliJ,Eclipse或Netbeans)可以幫助您編寫兩種方法的良好實現。

考慮到這一點,我想面試官已經問過如何將s1等於s2談論它,你誤解為s1(simble equals)s2 或者他已經明確地在紙上寫了算子==


如果面試官明確詢問如何做

s1 == s2 // returns true

在創建兩個對象之后

Student s1 = new Student();
Student s2 = new Student();

唯一的可能性是更改s1(或s2)的引用,如下所示:

Student s1 = new Student();
Student s2 = new Student();

s1 = s2;  // new added line , or the same if you write s2 == s1

s1 == s2  // now is true

但這是一個技巧,事實上你正在測試兩個不同的變量引用同一個對象。

您可以將類似的行為分配給兩個變量null或先前創建的另一個Student 基本上,對s1賦予s2相同引用的代碼的任何更改都將起作用。

這是一種技巧,但會滿足要求:

更改Student構造函數以拋出一些異常(我選擇了一個未經檢查的異常,因此我不必在throws子句中指定它):

public Student()
{
    throw new NullPointerException();
}

現在,假設我們被允許添加try-catch塊:

Student s1 = null;
Student s2 = null;
try {
    s1 = new Student(); 
    s2 = new Student();
}
catch (Exception e) {
}
System.out.println (s1==s2);

這將打印為true ,因為s1s2都為null

即使我們沒有捕獲異常,在兩個構造函數調用之后s1 == s2仍然是真的(實際上在第一個構造函數調用之后,因為第二個構造函數調用永遠不會被執行),但是我們必須在某個地方捕獲異常為了測試它。

正如這里已經回答的那樣, ==比較參考。 即它比較s1s2是否指向同一個對象。 由於您使用new來實例化s1s2 ,因此您的要求是不可能的

我看到的唯一合乎邏輯的解決方案是微不足道的:

s1 = new Student();
s2 = new Student();
s1=null;
s2=null;
System.out.println(s1==s2);

要么:

s1 = new Student();
s2 = new Student();
s1=s2;
System.out.println(s1==s2);

要么:

s1 = new Student();
s2 = new Student();
s2=s1;
System.out.println(s1==s2);

正如@ user7在評論中建議的那樣

==比較對象引用,它檢查兩個操作數是否指向同一個對象(不是等效對象, 同一個對象)。 所以我真的認為唯一的方法可能是這樣的:

@Override
public Student clone(){
    return this;
}

也許這會使==運算符按你的要求運行。 這對我來說是非常錯誤的,因為我不認為這是clone()方法的預期用途。 否則,我沒有任何關於如何制作的線索,因為你要求考慮在班級工作的約束。

如果無法使用clone() ,答案可能是:不可能這樣做。

當==運算符比較對象引用時,我認為s1和s2必須為null。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM