2.1 BigDecimal出错?都是精度的锅

要勇于精确计算的类BigDecimal,BigDecimal核心是精度,精度如果不匹配,结果大概率不会复合预期。

image.png

scale 需要与小数位匹配,否则会精度丢失,要比原来精度大,精度丢失会抛异常。否则,必须指定精度舍入的模式。

  1. private static void scaleProblem() {
  2. BigDecimal decimal = new BigDecimal("12.222");
  3. // BigDecimal result = decimal.setScale(12);
  4. // System.out.println(result);
  5. BigDecimal result = decimal.setScale(2, BigDecimal.ROUND_HALF_UP);
  6. System.out.println(result);
  7. }

BigDecimal 做除法时出现除不尽的情况,也会抛出异常,无限循环,也要做舍入结果。

  1. /**
  2. * <h2>BigDecimal 做除法时出现除不尽的情况</h2>
  3. * */
  4. private static void divideProblem() {
  5. // System.out.println(new BigDecimal(30).divide(new BigDecimal(7)));
  6. System.out.println(
  7. new BigDecimal(30).divide(new BigDecimal(7), 2,
  8. BigDecimal.ROUND_HALF_UP)
  9. );

精度问题导致比较结果和预期的不一致,虽然数值相等,但是比较值不相等,要使用compareTo进行比较。

  1. /**
  2. * <h2>精度问题导致比较结果和预期的不一致</h2>
  3. * */
  4. private static void equalProblem() {
  5. BigDecimal bd1 = new BigDecimal("0");
  6. BigDecimal bd2 = new BigDecimal("0.0");
  7. System.out.println(bd1.equals(bd2));
  8. System.out.println(bd1.compareTo(bd2) == 0);
  9. }

2.2 为啥老用不好日期计算?

SimpleDateFormat使用上常见的坑

  • 可以解析大于/等于它定义的时间精度,但是不能解析小于它定义的时间精度
  • 它是线程不安全的,在多线程环境下操作,会抛异常

线程不安全解决思路

  • 定义为局部变量
  • 使用ThreadLocal
  • 使用synchronized

可以解析大于它定义的精度,但是不能解析小于定义时间精度的时间,会抛出异常。

  1. /**
  2. * <h2>SimpleDateFormat 可以解析大于/等于它定义的时间精度</h2>
  3. * */
  4. private static void formatPrecision() throws Exception {
  5. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  6. String time_x = "2020-03-01 10:00:00";
  7. String time = "2020-03";
  8. System.out.println(sdf.parse(time_x));
  9. System.out.println(sdf.parse(time));
  10. }

SimpleDateFormat 存在线程安全问题

  1. /**
  2. * <h2>SimpleDateFormat 存在线程安全问题</h2>
  3. * */
  4. private static void threadSafety() {
  5. SimpleDateFormat sdf = new SimpleDateFormat(
  6. "yyyy-MM-dd HH:mm:ss");
  7. ThreadPoolExecutor threadPoolExecutor =
  8. new ThreadPoolExecutor(
  9. 10, 100, 1, TimeUnit.MINUTES,
  10. new LinkedBlockingDeque<>(1000)
  11. );
  12. while (true) {
  13. threadPoolExecutor.execute(() -> {
  14. String dateString = "2020-03-01 10:00:00";
  15. try {
  16. Date parseDate = sdf.parse(dateString);
  17. String dateString2 = sdf.format(parseDate);
  18. System.out.println(dateString.equals(dateString2));
  19. } catch (ParseException ex) {
  20. ex.printStackTrace();
  21. }
  22. });
  23. }
  24. }

线程不安全的原因calendar被共享,并且不是线程安全的,所以导致线程不安全。
image.png

2.3 我只想迭代元素,不需要索引呀

传统的for循环是怎样的

  • 如果是数组:通过数组长度,建立索引
  • 如果是集合:迭代器

传统的for循环存在怎样的弊端与劣势呢?

  • 我需要的是可迭代对象中的元素,并不需要元素的索引
  • 在嵌套环境下(多个可迭代对象) , 需要小心迭代器对象的正确性

for-each优于for

  • 只专注于迭代对象自身,而不考虑多余的索引
  • 任何实现Iterable接口的对象,都可以使用for-each循环处理
  • 进-步扩展: Java8 Iterable.forEach在一些场景下会比for-each更加方便

待遍历的集合

  1. private static Collection<Integer> left
  2. Arrays.asList(1, 2, 3, 4, 5, 6,
  3. private static Collection<Integer> righ
  4. Arrays.asList(1, 2, 3, 4, 5);

传统方式 - 使用索引

  1. int[] xyz = new int[]{1, 2, 3, 4, 5};
  2. for (int i = 0; i != xyz.length; ++i) {
  3. System.out.println(xyz[i]);
  4. }

传统方式 - 迭代器

  1. for (Iterator<Integer> i = left.iterator(); i.hasNext(); ) {
  2. System.out.println(i.next());
  3. }

嵌套迭代容易出现问题。l的next()方法应该从外层调用。

  1. for (Iterator<Integer> l = left.iterator(); l.hasNext(); ) {
  2. for (Iterator<Integer> r = right.iterator(); r.hasNext(); ) {
  3. System.out.println(l.next() * r.next());
  4. }
  5. }

正确的用法, 嵌套迭代

  1. for (Iterator<Integer> l = left.iterator(); l.hasNext(); ) {
  2. Integer tmp = l.next();
  3. for (Iterator<Integer> r = right.iterator(); r.hasNext(); ) {
  4. System.out.println(tmp * r.next());
  5. }
  6. }

foreach迭代。

  1. for (Integer l : left) {
  2. for (Integer r : right) {
  3. System.out.println(l * r);
  4. }
  5. }

Java8中的forEach

  1. // Java8 Iterable.forEach vs for-each
  2. for (Integer l : left) {
  3. square(l);
  4. }
  5. left.forEach(l -> square(l));
  6. left.forEach(ForeachOptimize::square);

2.4 如果不好好判等,集合存储就会乱套

Object的equals和hashcode方法

  • 默认的equals和hashcode实现是怎样的( Object中定义的) ?
  • 只重写equals方法真的会出错吗?

集合中元素的索引竟然也与equals方法相关

  • 类实现了compareTo方法,就需要实现equals方法
  • compareTo与equals的实现过程需要同步

User类

  1. public static class User implements Comparable<User> {
  2. private String name;
  3. private Integer age;
  4. public User() {}
  5. public User(String name, Integer age) {
  6. this.name = name;
  7. this.age = age;
  8. }
  9. public String getName() {
  10. return name;
  11. }
  12. public void setName(String name) {
  13. this.name = name;
  14. }
  15. public Integer getAge() {
  16. return age;
  17. }
  18. public void setAge(Integer age) {
  19. this.age = age;
  20. }
  21. @Override
  22. public boolean equals(Object obj) {
  23. if (obj instanceof User) {
  24. User user = (User) obj;
  25. return this.name.equals(user.name) && this.age == user.age;
  26. }
  27. return false;
  28. }
  29. @Override
  30. public int hashCode() {
  31. int result = name.hashCode();
  32. result = 31 * result + age;
  33. return result;
  34. }
  35. @Override
  36. public int compareTo(User o) {
  37. return (this.age - o.age) + this.name.compareTo(o.name);
  38. }
  39. }

不实现equals则不相等,因为比较内存地址,不定义hashcode方法,使用HashSet会出现元素重复,放到HashMap会出现null的情况。

  1. /**
  2. * <h2>实现/不实现 equals 方法和 hashcode 对于判等的影响</h2>
  3. * */
  4. private static void equalsAndHashcode() {
  5. User user1 = new User("qinyi", 19);
  6. User user2 = new User("qinyi", 19);
  7. System.out.println(user1.equals(user2));
  8. Set<User> userSet = new HashSet<>();
  9. userSet.add(user1);
  10. userSet.add(user2);
  11. Map<User, Integer> userIntegerMap = new HashMap<>();
  12. userIntegerMap.put(user1, 0);
  13. userIntegerMap.put(user2, 0);
  14. System.out.println(userSet.size());
  15. System.out.println(userIntegerMap.size());
  16. }

集合元素索引与 equals 方法相关,结果是一个0,一个1,indexOf()方法,某个元素在集合中的哪个位置,indexOf()使用的是equals进行比较,binarySearch()是使用compareTo方法。

  1. /**
  2. * <h2>集合元素索引与 equals 方法相关</h2>
  3. * */
  4. private static void compareToAndEquals() {
  5. List<User> users = new ArrayList<>();
  6. users.add(new User("qinyi", 10));
  7. users.add(new User("qinyi", 20));
  8. User user = new User("qinyi", 20);
  9. int index1 = users.indexOf(user);
  10. int index2 = Collections.binarySearch(users, user);
  11. System.out.println(index1);
  12. System.out.println(index2);
  13. }

2.5 使用 lombok 注解,没有达到预期该怎么办?

lombok注解
image.png

lombok原理
image.png

Java对象

  1. /**
  2. * <h1>Java Object</h1>
  3. * */
  4. @Data
  5. public class Personal {
  6. private String iPhone;
  7. private String name;
  8. private String userName;
  9. }

第一个坑:单字母驼峰lombok会把都变成小写,如果是iPhone会报错,应该避免单字母驼峰。

  1. /**
  2. * <h1>lombok 第一个坑</h1>
  3. * */
  4. private static void singleAlphabetHump() throws Exception {
  5. ObjectMapper mapper = new ObjectMapper();
  6. Personal personal = new Personal();
  7. personal.setIPhone("8.1");
  8. // {"name":null,"userName":null,"iphone":"8.1"}
  9. // System.out.println(mapper.writeValueAsString(personal));
  10. String json = "{\"name\": \"qinyi\"," +
  11. "\"userName\": \"qinyi-imooc\",\"iphone\":\"8.1\"}";
  12. Personal personal1 = mapper.readValue(json, Personal.class);
  13. System.out.println(personal1);
  14. }

第二个坑自动生成equals没有比较父类属性

  1. @Data
  2. @NoArgsConstructor
  3. @AllArgsConstructor
  4. public class Computer {
  5. private Integer id;
  6. private String name;
  7. }

子类继承父类Computer

  1. package com.imooc.java.escape.lombok_;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Data;
  4. import lombok.EqualsAndHashCode;
  5. import lombok.NoArgsConstructor;
  6. @EqualsAndHashCode(callSuper = true)
  7. @Data
  8. @NoArgsConstructor
  9. @AllArgsConstructor
  10. public class AppleComputer extends Computer {
  11. private long price;
  12. private String color;
  13. public AppleComputer(Integer id, String name, long price, String color) {
  14. super(id, name);
  15. this.price = price;
  16. this.color = color;
  17. }
  18. }

子类的lombok@Data注解生成的equal,默认是不加入父类字段判断,@EqualsAndHashCode(callSuper = true)使用这个注解,对callSuper声明为true,就会对父类的字段也会进行校验。

  1. /**
  2. * <h2>lombok 的第二个坑</h2>
  3. * */
  4. private static void equalsAndHashCodeBug() {
  5. AppleComputer computer1 = new AppleComputer(
  6. 1, "Mac Pro", 1L, "yellow"
  7. );
  8. AppleComputer computer2 = new AppleComputer(
  9. 2, "Mac Air", 1L, "yellow"
  10. );
  11. System.out.println(computer1.equals(computer2));
  12. }

2.6 怎么避免抽象类和接口选择失误呢?

共同的属性用抽象类表达,并且有状态的,特有的或者独立属性用接口去实现。
I’m I’m image.png

设计一个Worker类

  • Worker的工作、行为拆分为抽象类合理吗?为什么?
  • Worker的工作、行为拆分为接口合理吗?为什么?

抽象类、接口的含义和特性

  • 抽象类是子类的通用特性,包含了属性和行为;接口是定义行为,并不关心谁去实现
  • 抽象类是对类本质的抽象,表达的是is a的关系;接口是对行为的抽象,表达的是like a的关系

抽象类、接口的相同点

  • 接口中的方法( java8改变了这一语法)和抽象类中的抽象方法都不能有方法体,并且必须在子类中实现
  • 都可以被继承,但是不能被实例化

◆抽象类、接口的不同点

  • 使用时语法不同,抽象类使用extends ,接口则使用implements
  • 接口中只能定义常量,所以,不能表达对象状态,而抽象类可以
  • 接口中的方法必须是public类型的,而抽象类则没有限制
  • 类可以同时实现多个接口(间接解决了Java不支持多继承的we难题) , 但是只能继承一个抽象类

思考:抽象类和接口分别适用在什么样的场景中的呢?

抽象类BaseWork

  1. /**
  2. * <h1>每一个 Worker 最基本的属性</h1>
  3. * */
  4. public abstract class BaseWork {
  5. /** 起床时间 */
  6. protected int wakeupTime = 8;
  7. /** 上班打卡 */
  8. protected abstract void clockIn();
  9. /** 下班打卡 */
  10. protected abstract void clockOut();
  11. }

程序员基本工作接口

  1. /**
  2. * <h1>程序员的基本工作</h1>
  3. * */
  4. public interface IBaseWorking {
  5. void baseCoding();
  6. void baseTesting();
  7. default void config() {
  8. System.out.println("BaseWorking For Config");
  9. }
  10. static void time() {
  11. System.out.println(
  12. LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME)
  13. );
  14. }
  15. }

部分程序员的工作接口

  1. /**
  2. * <h1>部分程序员的工作</h1>
  3. * */
  4. public interface IExtraWorking {
  5. void extraCoding();
  6. void extraTesting();
  7. default void config() {
  8. System.out.println("ExtraWorking For Config");
  9. }
  10. static void time() {
  11. System.out.println(
  12. LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME)
  13. );
  14. }
  15. }

部分员工的兴趣

  1. /**
  2. * <h1>部分员工的兴趣</h1>
  3. * */
  4. public interface Interest {
  5. void playBall();
  6. }

员工类

  1. /**
  2. * <h1>员工类</h1>
  3. * */
  4. public class Worker extends BaseWork implements IBaseWorking, IExtraWorking {
  5. @Override
  6. protected void clockIn() {
  7. }
  8. @Override
  9. protected void clockOut() {
  10. }
  11. @Override
  12. public void baseCoding() {
  13. }
  14. @Override
  15. public void baseTesting() {
  16. }
  17. @Override
  18. public void config() {
  19. // 定义自己的 config
  20. }
  21. @Override
  22. public void extraCoding() {
  23. }
  24. @Override
  25. public void extraTesting() {
  26. }
  27. }

大多数worker都有爱好可以将工作和爱好结合到一起。

  1. public abstract class WorkAndInterest extends BaseWork {
  2. protected abstract void playBall();
  3. }