- 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 {}