2013-01-03 148 views
5

specification page,我看到%h調用Integer.toHexString(),但我找不到兩個說明符之間的任何實際區別。Java:格式說明符%x和%h之間有什麼區別?

你可以舉一個例子,在相同的輸入上使用to說明符會產生不同的結果嗎?

System.out.println(String.format("%1$h %1$x", 123)); 

這將打印

7b 7b 
+3

嘗試傳遞'null'到格式化。 –

+1

不,它調用'Integer.toHexString(arg.hashCode())'這是一個非常不同的東西。 –

+1

描述是非常不同的; '%h'在arg的hashCode上調用toHexString。 –

回答

11

%h符在其參數調用hashCode(只要不是null,當你拿到「空」),而%x符只是格式化它的參數爲十六進制整數。如果被格式化的東西不是整數,這會產生重大差異。在這裏看到的例子:

http://developer.android.com/reference/java/util/Formatter.html

特別是,你得到的整數相同的結果實際上是一個事實,即Integer.hashCode返回整數本身就是一個結果:

http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#hashCode%28%29

6

page you provided states:

'h'如果參數arg爲null,則結果爲「null 」。否則,通過調用Integer.toHexString(arg.hashCode())獲得結果。

「x」的結果被格式化爲十六進制整數

所以%h打印null如果所提供的目的是null,否則%h打印對象的哈希碼。而%x打印提供的int值的十六進制值。

編輯:在評論中指出:如果%x沒有給定值的IllegalFormatConversionException被拋出,如前所述這裏:

如果格式說明符包含一個轉換字符是不適用相應的參數,則會拋出IllegalFormatConversionException。

因此,基本上,你只需要看到你所提供的網頁... :)

+0

未傳遞整數時,'%x'做什麼? –

+1

它會拋出'IllegalFormatConversionException'。 – BalusC

+0

@BalusC值得測試 –

5

%h版畫在十六進制對象的哈希碼。

%x以十六進制打印一個數字。

對於Integer hashCode和值是相同的。對於Long,值和hashCode可以不同。

System.out.printf("%h%n", "hello world"); 
System.out.printf("%h%n", 0x1234567890L); 
System.out.printf("%x%n", 0x1234567890L); 

打印

6aefe2c4 
34567882 
1234567890 
相關問題