Java經(jīng)典用法總結(jié)
在Java編程中,有些知識(shí)并不能僅通過(guò)語(yǔ)言規(guī)范或者標(biāo)準(zhǔn)API文檔就能學(xué)到的,本文為大家羅列。
一、實(shí)現(xiàn)
1、現(xiàn)equals()
class Person { String name; int birthYear; byte[] raw; public boolean equals(Object obj) { if (!obj instanceof Person) return false; Person other = (Person)obj; return name.equals(other.name) && birthYear == other.birthYear && Arrays.equals(raw, other.raw); } public int hashCode() { ... } }
- 參數(shù)必須是Object類型,不能是外圍類。
- foo.equals(null) 必須返回false,不能拋NullPointerException。(注意,null instanceof 任意類 總是返回false,因此上面的代碼可以運(yùn)行。)
- 基本類型域(比如,int)的比較使用 == ,基本類型數(shù)組域的比較使用Arrays.equals()。
- 覆蓋equals()時(shí),記得要相應(yīng)地覆蓋 hashCode(),與 equals() 保持一致。
2、現(xiàn)hashCode()
class Person { String a; Object b; byte c; int[] d; public int hashCode() { return a.hashCode() + b.hashCode() + c + Arrays.hashCode(d); } public boolean equals(Object o) { ... } }
- 當(dāng)x和y兩個(gè)對(duì)象具有x.equals(y) == true ,你必須要確保x.hashCode() == y.hashCode()。
- 根據(jù)逆反命題,如果x.hashCode() != y.hashCode(),那么x.equals(y) == false 必定成立。
- 你不需要保證,當(dāng)x.equals(y) == false時(shí),x.hashCode() != y.hashCode()。但是,如果你可以盡可能地使它成立的話,這會(huì)提高哈希表的性能。
- hashCode()最簡(jiǎn)單的合法實(shí)現(xiàn)就是簡(jiǎn)單地return 0;雖然這個(gè)實(shí)現(xiàn)是正確的,但是這會(huì)導(dǎo)致HashMap這些數(shù)據(jù)結(jié)構(gòu)運(yùn)行得很慢。
3、實(shí)現(xiàn)compareTo()
class Person implements Comparable<Person> { String firstName; String lastName; int birthdate; // Compare by firstName, break ties by lastName, finally break ties by birthdate public int compareTo(Person other) { if (firstName.compareTo(other.firstName) != 0) return firstName.compareTo(other.firstName); else if (lastName.compareTo(other.lastName) != 0) return lastName.compareTo(other.lastName); else if (birthdate < other.birthdate) return -1; else if (birthdate > other.birthdate) return 1; else return 0; } }
總是實(shí)現(xiàn)泛型版本 Comparable 而不是實(shí)現(xiàn)原始類型 Comparable 。因?yàn)檫@樣可以節(jié)省代碼量和減少不必要的麻煩。
只關(guān)心返回結(jié)果的正負(fù)號(hào)(負(fù)/零/正),它們的大小不重要。
Comparator.compare()的實(shí)現(xiàn)與這個(gè)類似。
4、實(shí)現(xiàn)clone()
class Values implements Cloneable { String abc; double foo; int[] bars; Date hired; public Values clone() { try { Values result = (Values)super.clone(); result.bars = result.bars.clone(); result.hired = result.hired.clone(); return result; } catch (CloneNotSupportedException e) { // Impossible throw new AssertionError(e); } } }
- 使用 super.clone() 讓Object類負(fù)責(zé)創(chuàng)建新的對(duì)象。
- 基本類型域都已經(jīng)被正確地復(fù)制了。同樣,我們不需要去克隆String和BigInteger等不可變類型。
- 手動(dòng)對(duì)所有的非基本類型域(對(duì)象和數(shù)組)進(jìn)行深度復(fù)制(deep copy)。
- 實(shí)現(xiàn)了Cloneable的類,clone()方法永遠(yuǎn)不要拋CloneNotSupportedException。因此,需要捕獲這個(gè)異常并忽略它,或者使用不受檢異常(unchecked exception)包裝它。
- 不使用Object.clone()方法而是手動(dòng)地實(shí)現(xiàn)clone()方法是可以的也是合法的。
二、預(yù)防性檢測(cè)
1、預(yù)防性檢測(cè)(Defensive checking)數(shù)值
int factorial(int n) { if (n < 0) throw new IllegalArgumentException("Undefined"); else if (n >= 13) throw new ArithmeticException("Result overflow"); else if (n == 0) return 1; else return n * factorial(n - 1); }
- 不要認(rèn)為輸入的數(shù)值都是正數(shù)、足夠小的數(shù)等等。要顯式地檢測(cè)這些條件。
- 一個(gè)設(shè)計(jì)良好的函數(shù)應(yīng)該對(duì)所有可能性的輸入值都能夠正確地執(zhí)行。要確保所有的情況都考慮到了并且不會(huì)產(chǎn)生錯(cuò)誤的輸出(比如溢出)。
2、預(yù)防性檢測(cè)對(duì)象
int findIndex(List<String> list, String target) { if (list == null || target == null) throw new NullPointerException(); ... }
- 不要認(rèn)為對(duì)象參數(shù)不會(huì)為空(null)。要顯式地檢測(cè)這個(gè)條件。
3、預(yù)防性檢測(cè)數(shù)組索引
void frob(byte[] b, int index) { if (b == null) throw new NullPointerException(); if (index < 0 || index >= b.length) throw new IndexOutOfBoundsException(); ... }
不要認(rèn)為所以給的數(shù)組索引不會(huì)越界。要顯式地檢測(cè)它。
4、預(yù)防性檢測(cè)數(shù)組區(qū)間
void frob(byte[] b, int off, int len) { if (b == null) throw new NullPointerException(); if (off < 0 || off > b.length || len < 0 || b.length - off < len) throw new IndexOutOfBoundsException(); ... }
不要認(rèn)為所給的數(shù)組區(qū)間(比如,從off開始,讀取len個(gè)元素)是不會(huì)越界。要顯式地檢測(cè)它。
三、數(shù)組
1、填充數(shù)組元素
使用循環(huán):
// Fill each element of array 'a' with 123 byte[] a = (...); for (int i = 0; i < a.length; i++) a[i] = 123; (優(yōu)先)使用標(biāo)準(zhǔn)庫(kù)的方法: Arrays.fill(a, (byte)123);
2、復(fù)制一個(gè)范圍內(nèi)的數(shù)組元素
使用循環(huán):
// Copy 8 elements from array 'a' starting at offset 3 // to array 'b' starting at offset 6, // assuming 'a' and 'b' are distinct arrays byte[] a = (...); byte[] b = (...); for (int i = 0; i < 8; i++) b[6 + i] = a[3 + i]; (優(yōu)先)使用標(biāo)準(zhǔn)庫(kù)的方法: System.arraycopy(a, 3, b, 6, 8);
3、調(diào)整數(shù)組大小
使用循環(huán)(擴(kuò)大規(guī)模):
// Make array 'a' larger to newLen byte[] a = (...); byte[] b = new byte[newLen]; for (int i = 0; i < a.length; i++) // Goes up to length of A b[i] = a[i]; a = b;
使用循環(huán)(減小規(guī)模):
// Make array 'a' smaller to newLen byte[] a = (...); byte[] b = new byte[newLen]; for (int i = 0; i < b.length; i++) // Goes up to length of B b[i] = a[i]; a = b;
(優(yōu)先)使用標(biāo)準(zhǔn)庫(kù)的方法:
1a = Arrays.copyOf(a, newLen);
4、把4個(gè)字節(jié)包裝(packing)成一個(gè)int
int packBigEndian(byte[] b) { return (b[0] & 0xFF) << 24 | (b[1] & 0xFF) << 16 | (b[2] & 0xFF) << 8 | (b[3] & 0xFF) << 0; } int packLittleEndian(byte[] b) { return (b[0] & 0xFF) << 0 | (b[1] & 0xFF) << 8 | (b[2] & 0xFF) << 16 | (b[3] & 0xFF) << 24; }
5、把int分解(Unpacking)成4個(gè)字節(jié)
byte[] unpackBigEndian(int x) { return new byte[] { (byte)(x >>> 24), (byte)(x >>> 16), (byte)(x >>> 8), (byte)(x >>> 0) }; } byte[] unpackLittleEndian(int x) { return new byte[] { (byte)(x >>> 0), (byte)(x >>> 8), (byte)(x >>> 16), (byte)(x >>> 24) }; }
總是使用無(wú)符號(hào)右移操作符(>>>)對(duì)位進(jìn)行包裝(packing),不要使用算術(shù)右移操作符(>>)。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助。
相關(guān)文章
java Struts2框架下實(shí)現(xiàn)文件上傳功能
這篇文章主要為大家詳細(xì)介紹了java Struts2框架下實(shí)現(xiàn)文件上傳功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-10-10通過(guò)Java代碼來(lái)創(chuàng)建view的方法
本文給大家分享通過(guò)java代碼創(chuàng)建view的方法,以TextView為例創(chuàng)建控件的方法,需要的的朋友參考下吧2017-08-08Java 字符串反轉(zhuǎn)實(shí)現(xiàn)代碼
這篇文章主要介紹了 Java 字符串反轉(zhuǎn)實(shí)現(xiàn)代碼的相關(guān)資料,需要的朋友可以參考下2017-03-03SpringBoot整合Shiro兩種方式(總結(jié))
這篇文章主要介紹了SpringBoot整合Shiro兩種方式,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06JAVA通過(guò)HttpClient發(fā)送HTTP請(qǐng)求的方法示例
本篇文章主要介紹了JAVA通過(guò)HttpClient發(fā)送HTTP請(qǐng)求的方法示例,詳細(xì)的介紹了HttpClient使用,具有一定的參考價(jià)值,有興趣的可以了解一下2017-09-09java 中自定義OutputFormat的實(shí)例詳解
這篇文章主要介紹了java 中 自定義OutputFormat的實(shí)例詳解的相關(guān)資料,這里提供實(shí)例幫助大家學(xué)習(xí)理解這部分內(nèi)容,希望通過(guò)本文能幫助到大家,需要的朋友可以參考下2017-08-08Springboot?中的?Filter?實(shí)現(xiàn)超大響應(yīng)?JSON?數(shù)據(jù)壓縮的方法
這篇文章主要介紹了Springboot?中的?Filter?實(shí)現(xiàn)超大響應(yīng)?JSON?數(shù)據(jù)壓縮,定義GzipFilter對(duì)輸出進(jìn)行攔截,定義 Controller該 Controller 非常簡(jiǎn)單,主要讀取一個(gè)大文本文件,作為輸出的內(nèi)容,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-10-10Mybatis Select Count(*)的返回值類型介紹
這篇文章主要介紹了Mybatis Select Count(*)的返回值類型,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12