Java常见问题整理

  • Java三大特性(封装、继承、多态)
  • Integer的比较
  • String不可变
  • String, StringBuilder, StringBuffer的区别
  • String存储在哪里
  • 抽象与接口
  • Object通用方法

Java三大特性

  • 封装(Encapsulation):对外部隐藏细节,面向对象访问
  • 继承(Inheritance):
  • 多态(Polymorphism):

Integer的比较

Integer需要用equals方法来比较,为什么?先看一个现象

Integer m = 123;
Integer n = 123;
System.out.println(m == n); // true
------------------------------------------
Integer m = 323;
Integer n = 323;
System.out.println(m == n); // false

在 Java 8 中,Integer 存在缓存池中,大小默认为 -128~127。因为[-128,127]的比较都是同一个对象。

String不可变

String 被声明为 final,因此它不可被继承。内部使用 char 数组存储数据,该数组被声明为 final,这意味着 value 数组初始化之后就不能再引用其它数组

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];

final不可变的好处

  • ①String不可变,意味着hash值也不会变,无需重复计算hash
  • ②对于相同的String,可在String Pool中共用
  • ③线程安全,String天生具备线程安全

String, StringBuilder, StringBuffer的区别

1. 可变性

  • String 不可变
  • StringBuffer 和 StringBuilder 可变

2. 线程安全

  • String 不可变,因此是线程安全的
  • StringBuilder 不是线程安全的
  • StringBuffer 是线程安全的,内部使用 synchronized 进行同步

String存储在哪里

jdk1.8及以后:存储在堆中,并非在MetaSpace中

  • jdk1.8中:方法区在HotSpot中由本地内存的元空间(类型信息、字段、方法、常量)和(字符串常量池、静态变量)共同实现

抽象与接口

谈谈个人理解:接口往往优于抽象。在系统从0-1建设的过程中,往往先定义接口规范,随着业务的复杂,开始理解业务,抽象共性,提炼父类

  • 接口:定义规范
  • 抽象:收敛代码

Object通用方法

public final native Class<?> getClass()

public native int hashCode()

public boolean equals(Object obj)

protected native Object clone() throws CloneNotSupportedException

public String toString()

public final native void notify()

public final native void notifyAll()

public final native void wait(long timeout) throws InterruptedException

public final void wait(long timeout, int nanos) throws InterruptedException

public final void wait() throws InterruptedException

protected void finalize() throws Throwable {}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值