springboot源码解析,Java常用类使用总结

本文深入解析了Java中重要的几个概念:equals()方法用于对象内容比较,hashCode()用于哈希查找,wait()和notify()涉及线程同步,以及finalize()在对象回收时的作用。此外,还介绍了String类的使用,包括创建、常用方法以及与StringBuilder和StringBuffer的区别。文章最后讨论了Number类和Math类的相关操作,如整数与字符串的转换、随机数生成以及数学常量和函数。
摘要由CSDN通过智能技术生成

System.out.println(obj1.equals(obj2)); // false

// 对象引用,内存地址相同,相等,返回 true

Object obj3 = obj1;

System.out.println(obj1.equals(obj3)); // true

// String 类重写了 equals() 方法,用于比较两个字符串是否相等

String str1 = new String();

String str2 = new String();

System.out.println(str1.equals(str2)); // true

System.out.println(str1 == str2); // false

str1 = “a”;

str2 = “a”;

System.out.println(str1.equals(str2)); // true

System.out.println(str1 == str2); // true

}

}

== 和 equals() 方法的区别

  • == 可以比较两个基本数据类的变量的值是否相等,也可以比较对象的首地址是否相同。

  • equals() 方法只能比较对象的首地址是否相同。

hashCode()

hashCode() 方法用于获取对象的 hash 值。

hashCode() 方法用于哈希查找,可以减少在查找中使用 equals() 的次数,重写了equals方法一般都要重写 hashCode() 方法。这个方法在一些具有哈希功能的 Collection 中用到。

import java.util.ArrayList;

public class Test {

public static void main(String[] args) {

Object obj1 = new Object();

Object obj2 = new Object();

System.out.println(obj1.hashCode()); // 460141958

System.out.println(obj2.hashCode()); // 1163157884

String str = new String();

System.out.println(str.hashCode()); // 0

ArrayList arr = new ArrayList<>();

System.out.println(arr.hashCode()); // 1

}

}

一般必须满足 obj1.equals(obj2) == true。可以推出 obj1.hash Code() == obj2.hashCode(),但是hashCode 相等不一定就满足 equals。不过为了提高效率,应该尽量使上面两个条件接近等价。

wait()

wait() 方法让当前线程进入等待状态。直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法。

notify() 唤醒在该对象上等待的某个线程。

notifyAll() 唤醒在该对象上等待的所有线程。

import java.util.Date;

class WaitTest {

public static void main(String[] args) {

ThreadA threadA = new ThreadA(“threadA”);

synchronized (threadA) {

try {

// 启动线程

threadA.start();

System.out.println(Thread.currentThread().getName() + " wait() " + new Date());

// 主线程等待 ta 通过 notify 唤醒。

threadA.wait();// 不是使ta线程等待,而是当前执行 wait 的线程等待

System.out.println(Thread.currentThread().getName() + " continue " + new Date());

} catch (Exception e) {

e.printStackTrace();

}

}

}

}

class ThreadA extends Thread {

public ThreadA(String name) {

super(name);

}

@Override

public void run() {

synchronized (this) {

try {

Thread.sleep(1000); // 使当前线程阻塞1秒

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println(Thread.currentThread().getName() + " call notify()");

this.notify();

}

}

}

输出结果:

main wait() Sat Jul 24 13:03:57 CST 2021

threadA call notify()

main continue Sat Jul 24 13:03:58 CST 2021

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值