What's the best way to check if a String represents an integer in Java?

后端 未结 30 1933
野趣味
野趣味 2020-11-22 05:45

I normally use the following idiom to check if a String can be converted to an integer.

public boolean isInteger( String input ) {
    try {
        Integer.         


        
30条回答
  •  耶瑟儿~
    2020-11-22 06:29

    Did a quick benchmark. Exceptions aren't actually that expensivve, unless you start popping back multiple methods and the JVM has to do a lot of work to get the execution stack in place. When staying in the same method, they aren't bad performers.

     public void RunTests()
     {
         String str = "1234567890";
    
         long startTime = System.currentTimeMillis();
         for(int i = 0; i < 100000; i++)
             IsInt_ByException(str);
         long endTime = System.currentTimeMillis();
         System.out.print("ByException: ");
         System.out.println(endTime - startTime);
    
         startTime = System.currentTimeMillis();
         for(int i = 0; i < 100000; i++)
             IsInt_ByRegex(str);
         endTime = System.currentTimeMillis();
         System.out.print("ByRegex: ");
         System.out.println(endTime - startTime);
    
         startTime = System.currentTimeMillis();
         for(int i = 0; i < 100000; i++)
             IsInt_ByJonas(str);
         endTime = System.currentTimeMillis();
         System.out.print("ByJonas: ");
         System.out.println(endTime - startTime);
     }
    
     private boolean IsInt_ByException(String str)
     {
         try
         {
             Integer.parseInt(str);
             return true;
         }
         catch(NumberFormatException nfe)
         {
             return false;
         }
     }
    
     private boolean IsInt_ByRegex(String str)
     {
         return str.matches("^-?\\d+$");
     }
    
     public boolean IsInt_ByJonas(String str)
     {
         if (str == null) {
                 return false;
         }
         int length = str.length();
         if (length == 0) {
                 return false;
         }
         int i = 0;
         if (str.charAt(0) == '-') {
                 if (length == 1) {
                         return false;
                 }
                 i = 1;
         }
         for (; i < length; i++) {
                 char c = str.charAt(i);
                 if (c <= '/' || c >= ':') {
                         return false;
                 }
         }
         return true;
     }
    

    Output:

    ByException: 31

    ByRegex: 453 (note: re-compiling the pattern every time)

    ByJonas: 16

    I do agree that Jonas K's solution is the most robust too. Looks like he wins :)

提交回复
热议问题