Object类
equals ==
- Object 的 equals
单纯的比较两个对象变量是否引用了相同的对象—指向内存同一区域
public boolean equals(Object obj) {
return (this == obj);
}
- String 的 equals
/**
* Compares this string to the specified object. The result is {@code
* 将这个字符串和特定的对象比较,如果参数不空并且另一个字符串代表的字符序列和这个字符串的内容相同
* 就返回true
* true} if and only if the argument is not {@code null} and is a {@code
* String} object that represents the same sequence of characters as this
* object.
*
* @param anObject
* The object to compare this {@code String} against
*
* @return {@code true} if the given object represents a {@code String}
* equivalent to this string, {@code false} otherwise
*
* @see #compareTo(String)
* @see #equalsIgnoreCase(String)
*/
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
也就是说String 的 equals 方法单纯滴比较字符串的内容
public class EqualsTest {
public static void main(String[] args) {
String str1 = "abc";
String str2 = "abc";
String str3 = new String("abc");
String str4 = new String("abc");
System.out.println(str1.equals(str2));
System.out.println(str1.equals(str3));
System.out.println(str1.equals(str4));
Object ob = new Object();
}
}
- ==
public class EqualsTest {
public static void main(String[] args) {
String str1 = "abc";
String str2 = "abc";
String str3 = new String("abc");
String str4 = new String("abc");
System.out.println(str1==str2);
System.out.println(str1==str3);
System.out.println(str3==str4);
}
}
toString
- 作用:返回 表示对象值 的 字符串
- 最好在自定义类中覆盖这个方法
hashCode
哈希算法 略
包装类
基本数据类型
类型 | 存储所需空间 |
---|---|
整型 | |
byte | 1byte |
short | 2byte |
int | 4byte |
long | 8byte |
浮点型 | |
float | 4byte |
double | 8byte |
- char
- boolean
包装器类
- 自动装箱 自动拆箱
- Byte Short Integer Long Float Double Character Boolean
对于 -128~ +127的 Integer 和 Short 是代表同一个对象引用 - final 不可变 不可继承
- Integer Double 同时在表达式出现时 Integer拆箱→int→double→装箱Double
枚举类
public enum Size{S,M,L,XL};
- 声明意义:一个Size类有四个实例。
- 可以添加构造器、方法和实例域。
- values() 返回包含全部枚举值的数组。