ARTS是什么?
Algorithm:每周至少做一个LeetCode的算法题 Review:阅读并点评至少一篇英文文章 Tip:学习至少一个技术技巧 Share:分享一篇有观点和思考的技术文章
Algorithm
package leetcode;import java.util.ArrayList;import java.util.Comparator;import java.util.Optional;/*** @className: LeetCode08* @description:* 给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,* 垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器* 可以容纳最多的水。** 示例 1:* 输入:height = [1,1]* 输出:1** 示例 2:* 输入:height = [4,3,2,1,4]* 输出:16** 示例 3:* 输入:height = [1,2,1]* 输出:2* @author: Miluo* @date: 2021/4/16**/public class LeetCode08 {public int maxArea(int[] height) {ArrayList<Integer> list = new ArrayList<>();int x = 0,y = height.length - 1;int max = 0 ;while (x < y){if (height[x] < height[y]) {max = Math.max(max,height[x] * (y - x));x++;} else {max = Math.max(max,height[y] * (y - x));y--;}}return max;}}
Review
How to Make Your Reviewer Cry Using Java Optional
1.Old Fashioned Exception Handling
下面两个代码作用相同,但第二个更优雅简洁
Optional<User> userOptional = userDao.findByCellNumber(cellNumber);if (!userOptional.isPresent()) {throw new UserNotFoundException("...");} else {User user = userOptional.get();//...}
User user = userDao.findByCellNumber(cellNumber).orElseThrow(UserNotFoundException::new);
2.orElse and orElseGet Misuse
就是上篇Tip中所写的,无论Optional中是否为null,都会执行orElse中的方法,会影响性能
3.Using orElse(null)
这样使用没有意义,Optional是为了避免空指针异常,该方法看起来安全,但迟早会有空指针异常错误。
Tip
Spring Assert Statements:Spring Assert 可以帮助我们验证参数,当不符合时抛出运行时异常
虽然和Junit的Assert有着相同的名字,但是作用完全不一样,Junit等Assert是为了test,而Spring Assert是为了debug
notNull(Object object)/notNull(Object object, String message) ;//当 object 不为 null 时抛出异常,notNull(Object object, String message)方法允许//您通过 message 定制异常信息isTrue(boolean expression) / isTrue(boolean expression, String message);notEmpty(Collection collection) / notEmpty(Collection collection, String message);notEmpty(Map map) / notEmpty(Map map, String message) ;notEmpty(Object[] array, String message) / notEmpty(Object[] array, String message);hasLength(String text) / hasLength(String text, String message) ;hasText(String text) / hasText(String text, String message) text;isInstanceOf(Class clazz, Object obj) / isInstanceOf(Class type, Object obj, String message);isAssignable(Class superType, Class subType) / isAssignable(Class superType, Class subType, String message)//subType 必须可以按类型匹配于 superType,否则将抛出异常
