一.

1. 使用Boolean包装类型进行条件判断时注意

二. 技巧

1.使用Apache long包下的的StringUtil.equals(String str1, String str2) 代替String.equals(String str)可以避NullPointerException

3.Collections.sort()排序

Collections是一个工具类,sort是其中的静态方法,是用来对List类型进行排序的,它有两种参数形式:

3.1 传入List直接排序

需要List内的对象实现Comparable接口,默认从小到达正序排列

  1. public static <T extends Comparable<? super T>> void sort(List<T> list) {
  2. list.sort(null);
  3. }

3.2 传入List+Comparator的实现类

  1. public static <T> void sort(List<T> list, Comparator<? super T> c) {
  2. list.sort(c);
  3. }

Comparator用来对list内的元素排序,需要实现compare()方法,返回值为int类型

  • 大于0表示正序
  • 小于0表示逆序
  1. @Override
  2. public int compare(Integer o1, Integer o2) {
  3. return o2-o1;
  4. }

3.3 对无法运算的类型进行排序

利用上面第二种方法可以对无法运算的类型如枚举来排序,只需要在compare()方法内用if/else来划分并放回1和-1即可。根据实际需要,可以设计多层if/else结构。

  1. if (StringUtil.equalsIgnoreCase(o1, MyEnum.A.getType()
  2. && !StringUtil.equalsIgnoreCase(o2, MyEnum.A.getType()){
  3. return 1;
  4. } else {
  5. return -1;
  6. }

4 spring提供的CollectionUtils工具类

isEmpty()