在Java之中不僅僅存在兩個數字與兩個字符串之間的比較,還存在兩個對象之間的比較。
眾所周知,兩個數字之間的比較我們使用“==”,兩個字符串之間的比較我們使用“equals()”,那么兩個對象之間如何進行比較呢?既然要進行兩個對象之間的比較,那么就必須要實現兩個對象之間所有屬性內容的比較。
下面我們來看一下最為基礎的比較方式:
class Shoes{private String name;private double price;public Shoes(){}public Shoes(String title, double price){this.name = name;this.price = price;}public void setName(String name){this.name = name;}public String getName(){return this.name;}public void setPrice(double price){this.price = price;}public double getPrice(){return this.price;}public String getInfo(){return "名稱:" + this.name + ",價格:" + this.price;} } public class ObjectCompare{public static void main(String args[]){Shoes s1 = new Shoes("ADIDAS", 3980.0);Shoes s2 = new Shoes("NIKE", 1789.0);if(s1.getName().equals(s2.getName()) && s1.getPrice() == s2.getPrice()){System.out.println("是同一個對象!");}else{System.out.println("不是同一個對象!");}} }
運行結果:
由此可以發現,s1與s2兩個對象的屬性內容明顯不一樣,故不是同一個對象。若,s1與s2兩個對象的屬性內容完全一樣,則是同一個對象。在此,不再進行測試。
但是,從上述代碼中可以發現,此程序存在問題:主方法main()之中的程序邏輯過于復雜。我們寫代碼的原則就是在main()方法之中最好隱藏所有的細節邏輯,越簡單越好!
下面我們來看一下對象比較的實現:
class Shoes{private String name;private double price;public Shoes(){}public Shoes(String name, double price){this.name = name;this.price = price;}public void setName(String name){this.name = name;}public String getName(){return this.name;}public void setPrice(double price){this.price = price;}public double getPrice(){return this.price;}public boolean compare(Shoes sh){if(sh == null){return false;}if(this == sh){return true;}if(this.getName().equals(sh.getName()) && this.getPrice() == sh.getPrice()){return true;}else{return false;}}public String getInfo(){return "名稱:" + this.name + ",價格:" + this.price;} } public class ObjectCompare{public static void main(String args[]){Shoes s1 = new Shoes("ADIDAS", 3980.0);Shoes s2 = new Shoes("NIKE", 1789.0);if(s1.compare(s2)){System.out.println("是同一個對象!");}else{System.out.println("不是同一個對象!");}} }
運行結果:
在這里,大家需要注意一點的是,在進行對象比較的時候,一定要判斷是否為null、內存地址是否相同、屬性是否相同!
至此,Java之中的對象比較講解完畢,歡迎大家進行評論,謝謝!