簡體   English   中英

如何打印出 java 數據類型的類型、大小和范圍? 尤其是那些帶有修飾符的?

[英]how can i print out the type, size and range of a java data type ? esp those wtih modifiers?

目前我可以打印出a的字體大小和范圍;; 原始 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?

請幫忙。

這里有很多事情要澄清......:

  1. 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 , eg to implement a hash function. 沒有unsigned關鍵字,沒有無符號類型,當然也沒有相應的類型大小。

  2. Java 只有八種原始類型boolean , byte , char , double , float , int , long , short

  3. Java 也有八個相應的類,主要用於自動裝箱,但也提供有關原始類型的信息,如您的示例代碼所示。

  4. 修飾符(例如publicfinalstatic )僅影響原語的可見性和訪問語義,而不影響其基本屬性,例如其大小或范圍。

  5. 術語“數據類型”也指 object 類型。 Java has no equivalent for the C sizeof operator, since you do not need it to allocate memory as in C. 如果您確實需要了解 object 的 memory 封裝,請查看此處

Java 沒有 sizeof 運算符來查找原始數據類型的大小,但是除 Boolean 之外的所有 Java 原始包裝器都提供了一個大小為字節的數據類型除以八的 SIZE 常量。

class SizePrimitiveTypes
{
  public static void main (String[] args)
  {
    System.out.println("Size of byte: " + (Byte.SIZE/8) + " bytes.");
    System.out.println("Size of short: " + (Short.SIZE/8) + " bytes.");
    System.out.println("Size of int: " + (Integer.SIZE/8) + " bytes.");
    System.out.println("Size of long: " + (Long.SIZE/8) + " bytes.");
    System.out.println("Size of char: " + (Character.SIZE/8) + " bytes.");
    System.out.println("Size of float: " + (Float.SIZE/8) + " bytes.");
    System.out.println("Size of double: " + (Double.SIZE/8) + " bytes.");
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM