[英]Java: What's the difference between format specifiers %x and %h?
Looking at the specification page , I see that %h
calls into Integer.toHexString() , but I can't find any practical difference between the two specifiers. 看一下规范页面 ,我看到%h
调用了Integer.toHexString() ,但是我找不到两个说明符之间的任何实际区别。
Can you give an example where using the to specifiers on the same input yields different results? 您能举例说明在同一输入上使用to说明符会产生不同的结果吗?
System.out.println(String.format("%1$h %1$x", 123));
This prints 这打印
7b 7b
The %h
specifier invokes hashCode
on its argument (provided it is not null
, when you get "null"), whereas the %x
specifier just formats its argument as a hexadecimal integer. %h
说明符在其参数上调用hashCode
(假设它不是null
,当你得到“null”时),而%x
说明符只是将其参数格式化为十六进制整数。 This makes a major difference if the thing being formatted isn't an integer. 如果格式化的东西不是整数,这会产生很大的不同。 See the examples here: 请参阅此处的示例:
http://developer.android.com/reference/java/util/Formatter.html http://developer.android.com/reference/java/util/Formatter.html
In particular, the fact that you get the same results for integers is a result of the fact that Integer.hashCode
returns the integer itself: 特别是,整数获得相同结果的事实是Integer.hashCode
返回整数本身的结果:
http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#hashCode%28%29 http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#hashCode%28%29
The page you provided states: 您提供的页面说明:
'h' If the argument arg is null, then the result is "null". 'h'如果参数arg为null,则结果为“null”。 Otherwise, the result is obtained by invoking Integer.toHexString(arg.hashCode()). 否则,通过调用Integer.toHexString(arg.hashCode())获得结果。
and 和
'x' The result is formatted as a hexadecimal integer 'x'结果格式为十六进制整数
So %h
prints null
if the provided object was null
, otherwise %h
prints the hash code of the object. 于是%h
打印null
,如果所提供的对象是null
的,否则%h
打印对象的哈希码。 Whereas %x
prints the hex-value of the provided int
value. 而%x
打印提供的int
值的十六进制值。
Edit : as pointed out in the comments: if no value for %x
is given an IllegalFormatConversionException
is thrown, as stated here: 编辑 :如注释中所指出:如果没有给出%x
值,则抛出IllegalFormatConversionException
,如下所述:
If a format specifier contains a conversion character that is not applicable to the corresponding argument, then an IllegalFormatConversionException will be thrown. 如果格式说明符包含不适用于相应参数的转换字符,则将抛出IllegalFormatConversionException。
So basically, you'd just needed to read the page you provided... :) 所以基本上,你只需要阅读你提供的页面...... :)
%h
prints the hashcode of an object in hexidecimal. %h
以十六进制形式打印对象的哈希码。
%x
prints a number in hexidecimal. %x
以十六进制打印一个数字。
For Integer
the hashCode and the value are the same. 对于Integer
,hashCode和值是相同的。 For Long
the value and the hashCode can be different. 对于Long
,值和hashCode可以不同。
System.out.printf("%h%n", "hello world");
System.out.printf("%h%n", 0x1234567890L);
System.out.printf("%x%n", 0x1234567890L);
prints 版画
6aefe2c4
34567882
1234567890
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.