Java Coding Tips
Java Coding Tips
Use less target.setXX(source.getXX)
// when you want to use less target.setXX(source.getXX), same name
BeanUtils.copyProperties(source, target)
Manipulate Array
copy array
// most efficient(recommend)
void System.arraycopy(int[] srcArr, int srcBeginPos, int[] resArr, int resBeginPos, int length)
int[] Arrays.copyOfRange(int[] array, int start, int end)
// to increase array size, idle will be fullfilled with 0
int[] Arrays.copyOf(int[] srcArr, int newArrLength)
array -> list
int[] ints = {1,2,3};
List<Integer> list = Arrays.stream(ints).boxed().collect(Collectors.toList());
list -> array
String[] strings = list.stream().toArray(String[]::new);
Array<Integer> list = {0, 1, 2};
int[] array = list.stream().mapToInt(Integer::intValue).toArray()
distinct array
arr = Arrays.stream(arr).distinct().toArray();
sort object array in descending order
Integer[] cubes = new Integer[] { 8, 27, 64, 125, 256 }; Arrays.sort(cubes, Collections.reverseOrder());
Read more: https://www.java67.com/2016/07/how-to-sort-array-in-descending-order-in-java.html#ixzz8Greh6ggX
sort primitive array in descending order
Arrays.sort(arr);
int n = arr.length;
int temp;
for(int i = 0; i < n/2; i++) {
temp = arr[i];
arr[i] = arr[n - i - 1];
arr[n - i - 1] = temp;
}
Get max/min of an array
Arrays.stream(arr).max().getAsInt();
HashSet to List
Set<Integer> set = new HashSet();
set.add(1);
set.add(2);
List<Integer> list = set.stream().collect(Collectors.toList());
// when specify the type of list use toCollection(ArrayList::new)
set.stream().collect(Collectors.toCollection(ArrayList::new));
Bit Manipulate
get highest int
Integer.highestOneBit(int n);
set k-th bit as 0
n = ~ (1 << k) & n;
traverse all possibilties of set bits
for (int submask = mask; submask >= 0; submask = (submask - 1) & mask) {
// todo something
}
Use Optional in Java
Tip
- 可以在返回值里使用 optional ,提醒调用方这里返回的值可能为空,包装成 optional 对象就是强制要求调用者对空值情况进行判断处理。
- 连续取值。比如你接到一个层级很复杂的 json 对象,将其转换成 map 结构,一层一层的 get 需要判断 null ,用 Optional 的话,就算是内嵌深度是 10 层,也能用一行 optional 解决,避免出现嵌套 10 层 if-else 判断
需要从一个对象连续获取值的时候
String username = Optional.ofNullable(people).map(People::getName).orElse(null);
Arithmetic
ceil
// both a and b > 0, faster than
// res = x / y + (x % y != 0 ? 1 : 0);
res = (a + b - 1)/b
// more commonly, use
(int)Math.ceil((double)a/b);
// or
(int)Math.ceil(a*1.0/y);
Operator Precedence in Java
Level | Operator | Description | Associativity |
---|---|---|---|
16 | () [] . | parentheses array access member access | left-to-right |
15 | ++ -- | unary post-increment unary post-decrement | left-to-right |
14 | + - ! ~ ++ -- | unary plus unary minus unary logical NOT unary bitwise NOT unary pre-increment unary pre-decrement | right-to-left |
13 | () new | cast object creation | right-to-left |
12 | * / % | multiplicative | left-to-right |
11 | + - + | additive string concatenation | left-to-right |
10 | << >> >>> | shift | left-to-right |
9 | < <= > >= instanceof | relational | left-to-right |
8 | == != | equality | left-to-right |
7 | & | bitwise AND | left-to-right |
6 | ^ | bitwise XOR | left-to-right |
5 | | | bitwise OR | left-to-right |
4 | && | logical AND | left-to-right |
3 | || | logical OR | left-to-right |
2 | ?: | ternary | right-to-left |
1 | = += -= *= /= %= &= ^= |= <<= >>= >>>= | assignment | right-to-left |
0 | -> | lambda expression arrow | right-to-left |