How is ArrayOutOfBoundsException possible in String.valueOf(int)?

后端 未结 3 898
無奈伤痛
無奈伤痛 2021-02-05 03:30

Why does this code sometimes produce ArrayOutOfBoundsException? How is that even possible for String.valueOf(int)?

public static String ipToString(B         


        
3条回答
  •  感情败类
    2021-02-05 03:34

    I am leaving the code snippet here, as it still ought to be run faster than the original code - at a cost of memory - but be advised it doesn't actually fix the problem.

    private static final String[] STRING_CACHE = new String[256];
    
    static {
      for(int i = 0; i <= 255; i++) {
        STRING_CACHE[i] = String.valueOf(i);
      }
    }
    
    public static String ipToString(ByteString bs) {
      if (bs == null || bs.isEmpty()) {
        return null;
      } else {
        StringBuilder sb = new StringBuilder();
        boolean started = false;
        for (Byte byt : bs) {
          if (started) {
            sb.append(".");
          }
          sb.append(STRING_CACHE[byt & 0xFF]);
          started = true;
        }
    
        return sb.toString();
      }
    }
    

提交回复
热议问题