番石榴的對象類:Equals,HashCode和ToString

如果您有幸使用JDK 7 ,那么新的可用Objects類 ( 至少對我來說 )是實現“通用” Java對象方法(例如equals(Object) [with Objects.equals(Object,Object ) ], hashCode() [帶有Objects.hashCode(Object)或Objects.hash(Object…) ]和toString() [帶有Objects.toString(Object) ]以適當地覆蓋默認的Object實現。 我寫過有關使用Objects類的文章: JDK 7:New Objects類和Java 7 Objects-Powered Compact Equals 。

如果你還沒有使用Java 7,你最好的選擇可能是Apache的百科全書建設者ToStringBuilder和EqualsBuilder和HashCodeBuilder (如果你之前使用的Java版本,以J2SE 5)或番石榴 (如果你使用J2SE 5或后來)。 在本文中,我將研究如何使用Guava的Objects類來實現三種常見的方法equalshashCodetoString()

在沒有Guava或其他庫的幫助下,本文中討論的三種常見方法通常會突出顯示,如下面的代碼清單所示。 這些方法是使用NetBeans 7.1 beta生成的。

傳統員工

package dustin.examples;import java.util.Calendar;/*** Simple employee class using NetBeans-generated 'common' methods* implementations that are typical of many such implementations created* without Guava or other library.* * @author Dustin*/
public class TraditionalEmployee
{public enum Gender{ FEMALE, MALE };private final String lastName;private final String firstName;private final String employerName;private final Gender gender;/*** Create an instance of me.* * @param newLastName The new last name my instance will have.* @param newFirstName The new first name my instance will have.* @param newEmployerName The employer name my instance will have.* @param newGender The gender of my instance.*/public TraditionalEmployee(final String newLastName, final String newFirstName,final String newEmployerName, final Gender newGender){this.lastName = newLastName;this.firstName = newFirstName;this.employerName = newEmployerName;this.gender = newGender;}public String getEmployerName(){return this.employerName;}public String getFirstName(){return this.firstName;}public Gender getGender(){return this.gender;}public String getLastName(){return this.lastName;}/*** NetBeans-generated method that compares provided object to me for equality.* * @param obj Object to be compared to me for equality.* @return {@code true} if provided object is considered equal to me or*    {@code false} if provided object is not considered equal to me.*/@Overridepublic boolean equals(Object obj){if (obj == null){return false;}if (getClass() != obj.getClass()){return false;}final TraditionalEmployee other = (TraditionalEmployee) obj;if ((this.lastName == null) ? (other.lastName != null) : !this.lastName.equals(other.lastName)){return false;}if ((this.firstName == null) ? (other.firstName != null) : !this.firstName.equals(other.firstName)){return false;}if ((this.employerName == null) ? (other.employerName != null) : !this.employerName.equals(other.employerName)){return false;}if (this.gender != other.gender){return false;}return true;}/*** NetBeans-generated method that provides hash code of this employee instance.* * @return My hash code.*/@Overridepublic int hashCode(){int hash = 3;hash = 19 * hash + (this.lastName != null ? this.lastName.hashCode() : 0);hash = 19 * hash + (this.firstName != null ? this.firstName.hashCode() : 0);hash = 19 * hash + (this.employerName != null ? this.employerName.hashCode() : 0);hash = 19 * hash + (this.gender != null ? this.gender.hashCode() : 0);return hash;}/*** NetBeans-generated method that provides String representation of employee* instance.* * @return My String representation.*/@Overridepublic String toString(){return  'TraditionalEmployee{' + 'lastName=' + lastName + ', firstName=' + firstName+ ', employerName=' + employerName + ', gender=' + gender +  '}';}
}

盡管NetBeans 7.1 Beta在這里完成了繁重的工作,但仍必須維護此代碼,并使它們更具可讀性。 下一個類是相同的類,但是具有Guava支持的通用方法,而不是上面顯示的NetBeans生成的“典型”實現。

番石榴員工

package dustin.examples;/*** Simple employee class using Guava-powered 'common' methods implementations.* * I explicitly scope the com.google.common.base.Objects class here to avoid the* inherent name collision with the java.util.Objects class.* * @author Dustin*/
public class GuavaEmployee
{public enum Gender{ FEMALE, MALE };private final String lastName;private final String firstName;private final String employerName;private final TraditionalEmployee.Gender gender;/*** Create an instance of me.* * @param newLastName The new last name my instance will have.* @param newFirstName The new first name my instance will have.* @param newEmployerName The employer name my instance will have.* @param newGender The gender of my instance.*/public GuavaEmployee(final String newLastName, final String newFirstName,final String newEmployerName, final TraditionalEmployee.Gender newGender){this.lastName = newLastName;this.firstName = newFirstName;this.employerName = newEmployerName;this.gender = newGender;}public String getEmployerName(){return this.employerName;}public String getFirstName(){return this.firstName;}public TraditionalEmployee.Gender getGender(){return this.gender;}public String getLastName(){return this.lastName;}/*** Using Guava to compare provided object to me for equality.* * @param obj Object to be compared to me for equality.* @return {@code true} if provided object is considered equal to me or*    {@code false} if provided object is not considered equal to me.*/@Overridepublic boolean equals(Object obj){if (obj == null){return false;}if (getClass() != obj.getClass()){return false;}final GuavaEmployee other = (GuavaEmployee) obj;return   com.google.common.base.Objects.equal(this.lastName, other.lastName)&& com.google.common.base.Objects.equal(this.firstName, other.firstName)&& com.google.common.base.Objects.equal(this.employerName, other.employerName)&& com.google.common.base.Objects.equal(this.gender, other.gender);}/*** Uses Guava to assist in providing hash code of this employee instance.* * @return My hash code.*/@Overridepublic int hashCode(){return com.google.common.base.Objects.hashCode(this.lastName, this.firstName, this.employerName, this.gender);}/*** Method using Guava to provide String representation of this employee* instance.* * @return My String representation.*/@Overridepublic String toString(){return com.google.common.base.Objects.toStringHelper(this).addValue(this.lastName).addValue(this.firstName).addValue(this.employerName).addValue(this.gender).toString();}
}

如上面的代碼所示,Guava的使用提高了三種常用方法的實現的可讀性。 唯一不好的是需要在代碼中顯式定義Guava的Objects類,以避免與Java SE 7的Objects類發生命名沖突。 當然,如果不是使用Java 7,那么這不是問題,如果使用Java 7,則無論如何都應該使用標準版本。

結論

Guava通過其Objects類提供了一種構建更安全,更易讀的通用方法的好方法。 盡管我將對JDK 7項目使用新的java.util.Objects類,但是Guava的com.google.common.base.Objects類為在JDK 7之前的Java版本中工作提供了一個不錯的選擇。

參考: Guava的Objects類:來自JCG合作伙伴 Dustin Marx的Equals,HashCode和ToString,來自Inspired by Actual Events博客。

翻譯自: https://www.javacodegeeks.com/2012/11/guavas-objects-class-equals-hashcode-and-tostring.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/370491.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/370491.shtml
英文地址,請注明出處:http://en.pswp.cn/news/370491.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

此服務器的時鐘與主域控制器的時鐘不一致_中移動“超高精度時間同步服務器”開標,兩家中標...

8月25日,中國移動發布《2020年至2022年同步網設備集中采購_中標候選人公示》公告。兩家中標。同步網技術比較小眾,但是同步網是5G承載網的重要一環,分享一下,供大家參考。中標情況 標包1-時鐘同步設備中標候選人依次排序為&#x…

java 異常管理員_GitHub - kangZan/JCatch: Exception異常管理平臺,支持Java、PHP、Python等多種語言...

什么是JCatch當程序發生異常(Exception),處理方式一般是通過日志文件記錄下來,這種方式很容易被忽略,而且查詢起來比較麻煩。JCatch提供了一種方案,當程序發生異常時,通過JCatch平臺接口提交到JCatch平臺,由…

oled

gnd、vcc、clk、miso、rst、mosi、cs 轉載于:https://www.cnblogs.com/scrazy/p/7892733.html

使用html css js實現計算器

使用html css js實現計算器&#xff0c;開啟你的計算之旅吧 效果圖&#xff1a; 代碼如下&#xff0c;復制即可使用&#xff1a; <!DOCTYPE html><html lang"en"> <head> <meta charset"utf-8"> <style> /* 主體 */ .co…

面向對象的三個基本特征

面向對象的三個基本特征是&#xff1a;封裝、繼承、多態。封裝 封裝最好理解了。封裝是面向對象的特征之一&#xff0c;是對象和類概念的主要特性。封裝&#xff0c;也就是把客觀事物封裝成抽象的類&#xff0c;并且類可以把自己的數據和方法只讓可信的類或者對象操作&#xff…

Spring構造函數注入和參數名稱

在運行時&#xff0c;除非在啟用了調試選項的情況下編譯類&#xff0c;否則Java類不會保留構造函數或方法參數的名稱。 這對于Spring構造函數注入有一些有趣的含義。 考慮以下簡單的類 package dbg; public class Person {private final String first;private final String …

java學習文檔_資深程序員帶你深入了解JAVA知識點,實戰篇,PDF文檔

JAVA 集合JAVA 集合面對浩瀚的網絡學習資源&#xff0c;您是否為很難找到適合自己的學習資源而感到苦惱過&#xff1f;那么&#xff0c;您來對地方了。在這里我們幫助大家整理了一份適于輕松學習 Java 文章的清單。JVM文字太多&#xff0c;不便之處敬請諒解JAVA 集合文字太多&a…

java程序員電影_Java程序員必看電影:Java 4-ever

(Scene: A father and his son playing "throw-and-catch")(場景: 一位父親和兒子玩丟接球游戲)Narrator: They appear to be a perfect family旁白: 他們看起來像是一個完美的家庭(Scene: bedtime story)(場景: 床邊故事)Father: Export all OLE objects with the c…

深入理解softmax函數

Softmax回歸模型&#xff0c;該模型是logistic回歸模型在多分類問題上的推廣&#xff0c;在多分類問題中&#xff0c;類標簽 可以取兩個以上的值。Softmax模型可以用來給不同的對象分配概率。即使在之后&#xff0c;我們訓練更加精細的模型時&#xff0c;最后一步也需要用soft…

《第二章:深入了解超文本》

從本章開始要去除無用的話&#xff0c;只在筆記中記載要點----- 使用<a>元素創建一個超文本鏈接&#xff0c;鏈接到另一個Web頁面。 <a>元素的內容會成為Web頁面中可單擊的文本。 href屬性告訴瀏覽器鏈接的目標文件。 了解屬性 例&#xff1a;style的type屬性指定…

strcpy函數_錯誤更正(拷貝賦值函數的正確使用姿勢)

這是一篇對什么是C的The Rule of Three的錯誤更正和詳細說明。閱讀時間7分鐘。難度???雖然上一篇文章的閱讀量只有凄慘的兩位數&#xff0c;但是懷著對小伙伴負責的目的&#xff0c;必須保證代碼的正確性。這是大廚做技術自媒體的態度。前文最后一段代碼是這樣的&#xff1a…

將Java應用程序打包為一個(或胖)JAR

這篇文章的目標是一個有趣但非常強大的概念&#xff1a;將應用程序打包為單個可運行的JAR文件&#xff0c;也稱為一個或胖 JAR文件。 我們習慣了大型WAR歸檔文件&#xff0c;其中包含所有打包在某些公用文件夾結構下的依賴項。 使用類似于JAR的打包&#xff0c;情況有所不同&a…

學習java的第三天,猜字符的小程序

關于猜字符的小程序 主要實現&#xff1a;隨機輸出5個字母&#xff0c;用戶輸入猜測的字母&#xff0c;進行對比得出結果 主要有3個方法&#xff1a;主方法main(); 產生隨機字符的方法generate(); 比較用戶輸入的字符與隨機產生的字符的方法check&#xff08;&#xff09;&…

《Linux命令行與shell腳本編程大全 第3版》創建實用的腳本---10

以下為閱讀《Linux命令行與shell腳本編程大全 第3版》的讀書筆記&#xff0c;為了方便記錄&#xff0c;特地與書的內容保持同步&#xff0c;特意做成一節一次隨筆&#xff0c;特記錄如下&#xff1a;轉載于:https://www.cnblogs.com/guochaoxxl/p/7894995.html

python安裝包找不到setup_如何安裝沒有setup.py的Python模塊?

在系統上開始使用該代碼的最簡單的方法是&#xff1a;>將文件放入機器上的目錄中,>將該目錄的路徑添加到您的PYTHONPATH步驟2可以從Python REPL完成如下&#xff1a;import syssys.path.append("/home/username/google_search")您的文件系統的外觀示例&#xf…

Spring Batch中面向TaskletStep的處理

許多企業應用程序需要批處理才能每天處理數十億筆交易。 必須處理這些大事務集&#xff0c;而不會出現性能問題。 Spring Batch是一個輕量級且強大的批處理框架&#xff0c;用于處理這些大數據集。 Spring Batch提供了“面向TaskletStep”和“面向塊”的處理風格。 在本文中&a…

布局中常見的居中問題

說到布局除了浮動以及定位外還有一個不得不提的點&#xff0c;那就是居中&#xff0c;居中問題我們在網頁布局當中經常遇到&#xff0c;那么以下就是分為兩部分來講&#xff0c;一部分是傳統的居中&#xff0c;另一種則是flex居中&#xff0c;每個部分又通過分為水平垂直居中來…

unity json解析IPA后續

以前說到的&#xff0c;有很大的限制&#xff0c;只能解析簡單的類&#xff0c;如果復雜的就會有問題&#xff0c;從老外哪里看到一片博客&#xff0c;是將類中的list 等復雜對象序列化&#xff0c; using UnityEngine; using System.Collections; using System.Collections.…

改善代碼質量之內連臨時變量

待增轉載于:https://www.cnblogs.com/muyl/articles/6940896.html

python 矩陣元素相加_Numpy中元素級運算

標量與矩陣的運算:加法&#xff1a;values [1,2,3,4,5]values np.array(values) 5#現在 values 是包含 [6,7,8,9,10] 的一個 ndarray乘法&#xff1a;x np.multiply(some_array, 5)x some_array * 5矩陣與矩陣的運算:加法&#xff1a;對應元素相加&#xff0c;但形狀必須相…