Objects婧愮爜瑙h
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Objects婧愮爜瑙h相关的知识,希望对你有一定的参考价值。
鏍囩锛?a href='http://www.mamicode.com/so/1/field' title='field'>field
help arrays returns money 閬垮厤 stat plain ||1.equal()鏂规硶
Objects.equal鏂规硶鍙互閬垮厤jdk鐨別qual()鏂规硶鐨勫璞′负null鏃舵姏鍑虹┖鎸囬拡銆?/p>
1 Objects.equal("a", "a"); // returns true 2 Objects.equal(null, "a"); // returns false 3 Objects.equal("a", null); // returns false 4 Objects.equal(null, null); // returns true
鍏朵腑鐨勬簮鐮佸疄鐜颁负锛?/p>
1 public static boolean equal(@Nullable Object a, @Nullable Object b) { 2 return a == b || a != null && a.equals(b); 3 }
2.hash()绠楁硶
鐢ㄥ璞$殑鎵€鏈夊瓧娈典綔鏁e垪[hash]杩愮畻锛孏uava鐨?tt>Objects.hashCode(Object...)浼氬浼犲叆鐨勫瓧娈靛簭鍒楄绠楀嚭鍚堢悊鐨勩€侀『搴忔晱鎰熺殑鏁e垪鍊笺€備綘鍙互浣跨敤Objects.hashCode(field1, field2, …, fieldn)鏉ヤ唬鏇挎墜鍔ㄨ绠楁暎鍒楀€笺€?/p>
1 public static int hashCode(@Nullable Object... objects) { 2 return Arrays.hashCode(objects); 3 } 4 5 public static int hashCode(Object a[]) { 6 if (a == null) 7 return 0; 8 9 int result = 1; 10 11 for (Object element : a) 12 result = 31 * result + (element == null ? 0 : element.hashCode()); 13 14 return result; 15 }
3.toString()鏂规硶
濂界殑toString鏂规硶鍦ㄨ皟璇曟椂鏄棤浠蜂箣瀹濓紝浣嗘槸缂栧啓toString鏂规硶鏈夋椂鍊欏嵈寰堢棝鑻︺€備娇鐢?nbsp;Objects.toStringHelper鍙互杞绘澗缂栧啓鏈夌敤鐨則oString鏂规硶銆備緥濡傦細
Objects.toStringHelper(
this
).add(
"x"
,
1
).toString();
Objects.toStringHelper(
"MyObject"
).add(
"x"
,
1
).toString();
娉細搴曞眰浣跨敤涓€涓崟鍚戦摼琛ㄦ潵娣诲姞鍏冪礌銆?/p>
1 public String toString() { 2 boolean omitNullValuesSnapshot = this.omitNullValues; 3 String nextSeparator = ""; 4 StringBuilder builder = (new StringBuilder(32)).append(this.className).append(鈥榹鈥?span style="color: #000000;">); 5 6 for(Objects.ToStringHelper.ValueHolder valueHolder = this.holderHead.next; valueHolder != null; valueHolder = valueHolder.next) { 7 if (!omitNullValuesSnapshot || valueHolder.value != null) { 8 builder.append(nextSeparator); 9 nextSeparator = ", "; 10 if (valueHolder.name != null) { 11 builder.append(valueHolder.name).append(鈥?鈥?span style="color: #000000;">); 12 } 13 14 builder.append(valueHolder.value); 15 } 16 } 17 18 private static final class ValueHolder { 19 String name; 20 Object value; 21 Objects.ToStringHelper.ValueHolder next; 22 23 private ValueHolder() { 24 } 25 }
4.缁ф壙Comparable鎺ュ彛
Guava鎻愪緵浜咰omparisonChain鎵ц涓€绉嶆噿姣旇緝锛氬畠鎵ц姣旇緝鎿嶄綔鐩磋嚦鍙戠幇闈為浂鐨勭粨鏋滐紝灏嗚繑鍥炶绠楃粨鏋滐紝鍦ㄩ偅涔嬪悗鐨勬瘮杈冭緭鍏ュ皢琚拷鐣ャ€?/p>
1 @Override 2 public int compareTo(Account o) { 3 return ComparisonChain.start() 4 .compare(this.accountName, o.accountName) 5 .compare(this.money, o.money).result(); 6 }
以上是关于Objects婧愮爜瑙h的主要内容,如果未能解决你的问题,请参考以下文章