文章目录
1、break loop; continue loop;
//不支持goto loop
loopName:
for(;;){
innerLoopName:
for(;;){
...
if(){
//结束名称为loopName的循环
break loopName;
}
}
}
2、可以利用静态内部类实现测试
public interface FooAOPService {
default void defaultMethod() {
System.out.println("this is from default method defined from interface");
}
public static class Tester {
public static void main(String[] args){
FooAOPService service = new FooAOPServiceImpl();
service.defaultMethod();//对interface的实现类,测试实现方法defaultMethod的功能。可以避免在每个实现类中都写一个main方法。
}
}
}
3、multi-catch工具
在保证清晰性的前提下简化代码
try {
TimeUnit.NANOSECONDS.sleep(10);
FileInputStream fileInputStream = new FileInputStream(new File("ss.txt"));
} catch (FileNotFoundException | InterruptedException e) {//multi-catch
e.printStackTrace();
}
4、移位符
JAVA中没有无符号左移运算符(<<<), 为什么??
JLS中要求,对于被移动数类型为int时,移动位数s的范围在[0,31]之间(对于被移动数类型是long的话,s在[0,63]之间)。
测试代码见移位运算符功能测试
A.n << s : 带符号数n左移s位,低位补零,符号位不变。
转为十进制运算=n*(2的s次)
B.n >> s : 带符号数n右移s位,高位符号位不变,数值位高位补零。
转为十进制运算=n/(2的s次)
C.n >>> s : 不带符号数n右移s位,没有符号位 ,高位补零。
无符号右移(>>>)转为十进制运算:
若n为正数,n/(2的s次)
若n为负数且s是int类型:(n >> s) + (2 << ~s)
若n为负数且s是long类型:(n >> s) + (2L << ~s)
注意:
1、添加的加数是为了抵消符号位运算的符号位移动的作用效果。The added term (2 << ~s) or (2L << ~s) cancels out the propagated sign bit.
2、若s是int类型,则 ~s=31-s(int s=3;~s=31-s=28);若s是long类型,则~s=62-s。Note that, because of the implicit masking of the right-hand operand of a shift operator, ~s as a shift distance is equivalent to 31-s when shifting an int value and to 63-s when shifting a long value.
5. String.compareTo 返回值 {0,正数,负数}
1、CompareTo返回两个字符串中位置k处的两个字符值的ascii差,即值:
this.charAt(k)- another.charAt(k)
2、如果没有不同的索引位置,那么在词典中,较短的字符串在较长的字符串之前。在这种情况下,CompareTo返回字符串长度的差,即值:
this.length()- another.length()
3、字符的值和长度都相等时,返回 0
System.out.println("123".compareTo("234"));// 1 != 2,返回ascii码之差: 1
System.out.println("123".compareTo("345"));// 1 != 3,返回ascii码之差: 2
System.out.println("345".compareTo("123"));
System.out.println("234".compareTo("234567"));//前n位一样,返回长度之差
System.out.println("234567".compareTo("234"));
6. 时间控制,任意增减指定个月、日期、年,指定任意日期
Calendar turnaroundCal = Calendar.getInstance();
turnaroundCal.setTime(new Date());
turnaroundCal.add(Calendar.MONTH, 2); // 设置时间为两个月后
turnaroundCal.set(Calendar.DATE, 1); // 设置日期为1号
7.排序
stream.sorted
不要用,不会对整个序列进行重排序,只比较前后位置的元素并将交换