1、Math.abs()不一定会返回正数
String str = "";int result = Math.abs(str.hashCode()) % 3; //有可能会返回负数哦Math.abs(Integer.MIN_VALUE);//返回的就是负数,因为内存溢出了
2、不要在finally块中使用return、或者throw异常
在finally中使用return或者throw异常时,会吞掉try或catch中的结果。
//在finally中使用returnpublic static void main(String[] args){System.out.println(test());//输出"finally"}public static String test(){try{int resutl = 100/0;return "try";}catch(Exception e){return "catch";}finally {return "finally";}}
//在finally中throw异常public static void main(String[] args) throws Exception {throwTest(); //抛出ClassNotFoundException}public static void throwTest() throws Exception {try{throw new RuntimeException();}catch(Exception e){throw new ClassCastException();}finally {throw new ClassNotFoundException();}}
3、catch了InterruptException后要根据情况决定是否重新调用Thread.interrupt()方法
线程Thread中有一个标识flag用来记录当前线程是否被中断,默认为false,通过Thread.isInterrupt()方法可以获取该标识,当调用了Thread.interrupt方法时,会将该标识改为false,该线程会在合适的时机抛出InterruptException,且将该标识重新改为false(蓝色字体部分的内容尚未验证)。
//调用Thread.sleep()方法时会抛出InterruptException异常。public static void main(String[] args) {Runnable thread = new MyThread();Thread t1 = new Thread(thread);t1.start();t1.interrupt();System.out.println("t1.isInterrupted(): "+ t1.isInterrupted());try {TimeUnit.SECONDS.sleep(4);} catch (InterruptedException e) {//此处catch了InterruptedException,但是我只是为了sleep而已,并非要在这里处理中断的业务逻辑,所以应当重新调用Thread.interrupt()方法再次标识为中断Thread.currentThread.interrupt();}t1.interrupt();System.out.println("t1.isInterrupted(): "+ t1.isInterrupted());}
4、禁止使用BigDecimal(double)的方式把一个Double转换为BigDecimal
public static void main(String[] args) {BigDecimal bigDecimal = new BigDecimal(0.1);System.out.println(bigDecimal.toString());//结果是:0.1000000000000000055511151231257827021181583404541015625}//得到的结果并非是想要的0.1,可能会导致到意想不到的结果
//优先推荐入参为 String 的构造方法,或使用 BigDecimal.valueOf() 方法public static void main(String[] args) {BigDecimal bigDecimal = new BigDecimal("0.1");BigDecimal bigDecimal1 = BigDecimal.valueOf(0.1);System.out.println(bigDecimal.toString()+"------"+bigDecimal1.toString());//结果是:0.1------0.1}
