我怎样才能打印出java数据类型的类型、大小和范围?特别是那些带有修饰符的?
目前我可以打印出 a;; 的字体大小和范围除 bollean 之外的原始 java 数据类型使用以下方法。
public class sizJ {
public static void display(Class<?> type, int size, Number min, Number max) {
System.out.printf("%-6s %-2s %-20s %s\n", type, size, min, max);
}
public static void main(String[] args) {
System.out.printf("%s %-2s %-20s %s\n","type","size","min","max");
display(Byte.TYPE, Byte.SIZE, Byte.MIN_VALUE, Byte.MAX_VALUE);
display(Character.TYPE, Character.SIZE, (int) Character.MIN_VALUE, (int) Character.MAX_VALUE);
display(Integer.TYPE, Integer.SIZE, Integer.MIN_VALUE, Integer.MAX_VALUE);
display(Float.TYPE, Float.SIZE, Float.MIN_VALUE, Float.MAX_VALUE);
display(Double.TYPE, Double.SIZE, Double.MIN_VALUE, Double.MAX_VALUE);
display(Long.TYPE, Long.SIZE, Long.MIN_VALUE, Long.MAX_VALUE);
display(Double.TYPE, Double.SIZE, Double.MIN_VALUE, Double.MAX_VALUE);
display(SignedDouble.TYPE, Double.SIZE, Double.MIN_VALUE, Double.MAX_VALUE);
}
。
从论坛复制的代码
问题是我如何打印相同的内容,例如signed long或signed char或unsigned int?
请帮忙。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里有很多事情需要澄清...:
Java 没有像 C 那样的无符号原语 - 顺便说一句,对于那些需要做大量 bit-twiddling,例如实现哈希函数。没有
unsigned
关键字,没有无符号类型,当然也没有对应的类型大小。Java 只有八种基本类型:
布尔
、字节
、字符
、双精度
、浮点
、int
>,长
,短
Java也有八个对应的类,主要用于自动装箱,还提供有关原语的信息类型,如您的示例中所示
修饰符(例如
public
、final
、static
)仅影响原语的可见性和访问语义 - 不影响 它的基本属性,例如它的大小或范围。术语“数据类型”也指对象类型。 Java 没有 C
sizeof
运算符的等效项,因为您不需要像 C 中那样用它来分配内存。如果您确实需要知道对象的内存占用量,请查看此处。Lots of things to clarify here...:
Java does not have unsigned primitives like C - a significant issue, by the way, for those who need to do a lot of bit-twiddling, e.g. to implement a hash function. There is no
unsigned
keyword, no unsigned types and, of course, no corresposing type size.Java only has eight primitive types:
boolean
,byte
,char
,double
,float
,int
,long
,short
Java also has eight corresponding classes, primarily used for autoboxing, but also to provide information on the primitive types, as seen in your sample code.
Modifiers (e.g.
public
,final
,static
) only affect the visibility and access semantics of a primitive - not its basic properties, such as its size or range.The term "data type" also refers to object types. Java has no equivalent for the C
sizeof
operator, since you do not need it to allocate memory as in C. If you do need to know the memory footprint of an object have a look here.Java 没有 sizeof 运算符来查找原始数据类型的大小,但除 Boolean 之外的所有 Java 原始包装器都提供一个以位为单位的 SIZE 常量,该常量可以除以 8 以获得以字节为单位的数据类型的大小。
Java has no sizeof operator to find the size of primitive data types but all Java primitive wrappers except Boolean provide an SIZE constant in bits that could be divided by eight to get the size of a data type in bytes.