Java Tips

2020-05-16  本文已影响0人  Lyudmilalala

Basic Java

  1. ""Integer.MAX_VALUE + 1 = Integer.MIN_VALUE. Integer.MIN_VALUE - 1 = Integer.MAX_VALUE."" Be careful about the overflow.

  2. Use lambda to write a customized Comparator

// Implement a Comparator for sorting an array of elements representing their features in an array of size 2
Arrays.parallelSort(people, ( (int[] a, int[] b) -> {
    if( a[0]==b[0] ) {
        return a[1] - b[1];
    } else{
      return b[0] - a[0];
    }
}));
  1. 使用entrySet同时得到Map的Key和Value
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
      System.out.println ( entry.getKey() + ":" + entry.getValue() );
}
  1. 使用Iterator做到在遍历途中删除List或Map的元素
// remove an element in Map which has value = -1
for (Iterator<Map.Entry<Integer, Integer>> itm = map.entrySet().iterator(); itm.hasNext(); ) {
    Map.Entry<Integer, Integer> entry = itm.next();
    if (entry.getValue().intValue() == -1 ) {
        itm.remove();
    }
}
// remove an element in List which contains substring "hello"
for (Iterator<String> itl = list.iterator(); itl.hasNext(); ) {
    String s = itl.next();
    if ( s.contains("hello") ) {
        itl.remove();
    }
}
  1. Arrays.asList()不适用于基本数据类型(byte, short, int, long, float, double, boolean)的array,但如果直接传入array中值则有效
//both valid
List<Integer> list1 = Arrays.asList(new Integer[]{nums[a], nums[b], nums[c], nums[d]});
List<Integer> list2 = Arrays.asList(nums[a], nums[b], nums[c], nums[d]);
  1. split by一个或多个空格
String[] split = input.trim().split("\\s+");
  1. Random Generator
Random r = new Random();
return r.nextInt(7);  //0-6
return r.nextInt(7)+1;  //1-7
  1. Switch不支持Long。原因就是 switch 对应的 JVM 字节码 lookupswitch、tableswitch 指令只支持 int 类型。

  2. 内部类的函数对各层级同名参数的调用

public class Outer {
    private int age = 12;

    class Inner {
        private int age = 13;
        public void print() {
            int age = 14;
            System.out.println("local variable:" + age);
            System.out.println("inner class variable:" + this.age);
            System.out.println("outer class variable:" + Outer.this.age);
        }
    }

    public static void main(String[] args) {
        Outer.Inner in = new Outer().new Inner();
        in.print();
        //result
        //local variable:14
        //inner class variable:13
        //outer class variable:12
    }
}
  1. 如果整型字面量的值在-128到127之间,那么自动装箱时不会new新的Integer对象,而是直接引用常量池中的Integer对象,超过范围 a1==b1的结果是false。
    String类如果直接赋予常量值的话,则值同样进入常量池。
public static void main(String[] args) {

    Integer a = new Integer(3);
    Integer b = 3;  // 自动装箱,进入常量池
    int c = 3;
    System.out.println(a == b); // false 两个引用没有引用同一对象
    System.out.println(a == c); // true a自动拆箱成int类型再和c比较
    System.out.println(b == c); // true

    Integer a1 = 128;
    Integer b1 = 128;
    System.out.println(a1 == b1); // false

    Integer a2 = 127;
    Integer b2 = 127;
    System.out.println(a2 == b2); // true


    String aa = "ab"; // 创建引用aa,放入常量池中
    String a = new String("ab"); // 创建引用a,放一份在静态常量池中,一份在堆内存
    String b = new String("ab"); // 创建引用b,放一份在静态常量池中,一份在堆内存,对象的内容与a一样
    String bb = "ab"; // 从常量池中查找
    System.out.println(a == b); // false
    System.out.println(a == aa); // false
    System.out.println(aa == bb); // true
}
  1. 反射 (Reflection)
public class Get {

    class Student {
        private int id;
        String name;
        protected boolean sex;
        public float score;
    }

    //获取反射机制三种方式
    public static void main(String[] args) throws ClassNotFoundException {
        //方式一(通过建立对象)
        Student stu = new Student();
        Class classobj1 = stu.getClass();
        System.out.println(classobj1.getName());
        //方式二(所在通过路径-相对路径)
        Class classobj2 = Class.forName("fanshe.Student");
        System.out.println(classobj2.getName());
        //方式三(通过类名)
        Class classobj3 = Student.class;
        System.out.println(classobj3.getName());
    }
}

SpringBoot

  1. JPA多对多关系

都使用了Lombdk则会报错,因此只在主要的类上使用,另一个自己写Getter,Setter
JsonIgnore不生效, 仍会列出Set

# Platform Entity, use @Data
@ManyToMany(fetch=FetchType.EAGER)
@JoinTable(
    name = "platform_user", 
    joinColumns = @JoinColumn(name = "platform_id"), 
    inverseJoinColumns = @JoinColumn(name = "user_id")
)
Set<Users> users;
# User Entity, do not use @Data
@ManyToMany(mappedBy = "users", fetch=FetchType.EAGER)
    Set<Platform> platforms;
上一篇下一篇

猜你喜欢

热点阅读