Java常用类
一、内部类
- 成员内部类
- 静态内部类
- 局部内部类
- 匿名内部类
概念: 在一个类的内部再定义一个完整的类
public class Body{
// 只能有一个Public class
class Header{
}
}
特点:
-
编译之后可输出成独立的字节码文件
Body.class Body$Header.class
-
内部类可直接访问外部类的私有成员,而不破坏封装
-
可为外部类提供内部的功能组件
1.1、成员内部类
- 在类的内部定义,与实例变量、实例方法同级别的类
- 外部类的一个实例部分,创建内部类对象时,必须依赖外部类对象
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
- 或者
Outer.Inner inner = new Outer().new Inner();
- 当外部类、内部类存在重名属性时,会优先访问内部类属性
- 成员内部类不能定义静态成员,但可以定义静态常量。
static final
public class Outer {
//实例变量
private String name = "张三";
private int age = 10;
//内部类
class Inner{
private String address = "北京";
private String phone = "110";
private String name = "李四";
//private static final String country = "中国";
//方法
public void show(){
//打印外部类的属性 Outer.this
System.out.println(Outer.this.name);
System.out.println(Outer.this.age);
//打印内部类的属性
System.out.println(this.address);
System.out.println(this.phone);
}
}
}
public class Test {
public static void main(String[] args) {
//1.创建外部对象
Outer outer = new Outer();
//2.创建内部对象
Outer.Inner inner = outer.new Inner();
//一步到位
//Outer.Inner inner = new Outer().new Inner();
inner.show();
}
}
1.2、静态内部类
在成员内部类的基础上,添加一个static inner
,静态内部类其实相当于一个外部类。
- 不依赖外部类对象,可直接创建或通过类名访问,可声明静态成员。
- 访问外部类的实例变量——实例化一个外部类对象,
.
的方式访问 - 访问静态内部类的变量——
this.变量名
- 访问静态内部类的静态变量——
类名.变量名
- 访问外部类的实例变量——实例化一个外部类对象,
public class Outer {
// 外部类实例变量
private String name = "张三";
private int age = 10;
// 静态内部类和外部类相同
static class Inner{
private String address = "北京";
private String phone = "110";
// 静态内部类的静态成员
private static String name = "李四";
// 方法
public void show(){
//打印外部类的属性
//创建对象
Outer outer = new Outer();
System.out.println(outer.name);
//打印
System.out.println(outer.age);
//打印内部类的属性
System.out.println(this.address);
System.out.println(this.phone);
//调用静态内部类的静态属性
System.out.println(Inner.name);
}
}
}
public class Test {
public static void main(String[] args) {
//直接创建静态内部类对象
Outer.Inner inner = new Outer.Inner();
inner.show();
}
}
1.3、局部内部类
定义在外部类方法中,作用范围和创建对象范围仅限于当前方法。
- 局部内部类访问外部类 当前方法中的局部变量时,因无法保障变量生命周期与自身相同,变量必须修饰为
final
- 限制类的使用范围
- 局部内部类的实例变量——
this.变量名
- 局部变量——
属性名 (final修饰变成常量)
- 外部类的实例变量——
Outer.this.变量名
- 局部内部类的实例变量——
public class Outer {
//外部类的实例变量
private String name = "张三";
private int age = 10;
public void showOuter(){
//定义局部变量
final String address = "深圳";
//局部内部类
class Inner {
//局部内部类实例变量
private String phone= "1111";
private String email = "123@qqw.com";
private final static int count = 2000;
public void showInner(){
//访问外部类的属性
//非静态方法访问非静态属性,可以直接访问,如果是静态方法,则变成对象.
// Outer outer = new Outer();
// System.out.println(outer.name);
// System.out.println(outer.age);
System.out.println(Outer.this.name);
System.out.println(Outer.this.age);
//访问内部类的属性
System.out.println(this.phone);
System.out.println(this.email);
//访问局部变量
//jdk1.8自动增加final修饰符
System.out.println(address);
//System.out.println("深圳");
}
}
//如果只调用showOuter方法,只是起到了定义局部内部类的作用
Inner inner = new Inner();
inner.showInner();
}
}
public class Test {
public static void main(String[] args) {
Outer outer = new Outer();
outer.showOuter();
}
}
1.4、匿名内部类
- 没有类名的局部内部类(一切特征都与局部内部类相同)
- 必须继承一个父类或者实现一个接口。
- 定义类、实现类、创建对象的语法合并,只能创建一个该类的对象
- 优点:减少代码量
- 缺点:可读性较差
//定义一个接口
// Usb.java
public interface Usb {
void service();
}
//正常实现接口
//Mouse.java
public class Mouse implements Usb{
@Override
public void service() {
System.out.println("连接电脑成功,鼠标开始工作");
}
}
public class TestUsb {
public static void main(String[] args) {
// //创建接口类型的变量
// Usb usb = new Mouse();
// usb.service();
//new Mouse().service();
// //局部内部类 main()方法
// class Fan implements Usb{
// @Override
// public void service() {
// System.out.println("连接电脑成功,风扇开始工作");
// }
// }
// Usb usb = new Fan();
// usb.service();
//匿名内部类和局部内部类是一样
//创建一次就可以,把定义类,实现类,创建对象合并
Usb usb = new Usb(){
@Override
public void service() {
System.out.println("连接电脑成功,风扇开始工作");
}
};
usb.service();
}
}
二、Object类
- 超类、基类、所有类的直接或间接父类,位于继承树的顶层
- 默认继承Object类
- Object类型可以存储任何对象
- 作为参数
- 作为返回值
1.getClass()方法
-
public final class<?> getClass()
-
返回引用中存储的实际对象类型
-
应用:通常用于判断两个引用中实际存储对象类型是否一致
2.hashCode()方法
-
public int hashCode()
-
返回对象的哈希码值
-
哈希值根据对象的地址或字符串或数字使用hash算法计算出来的int类型的数值
- 只要在执行Java应用程序时多次在同一个对象上调用该方法,
hashCode
方法必须始终返回相同的整数 - 如果根据
equals(Object)
方法两个对象相等,则在两个对象中的每个对象上调用hashCode
方法必须产生相同的整数结果
- 只要在执行Java应用程序时多次在同一个对象上调用该方法,
3.toString()方法
public String toString()
- 返回对象的字符串表示形式。
getClass().getName() + "@" + Integer.toHexString(hashCode())
- 可以根据程序需求可以覆盖该方法。
4.equals()方法
-
public boolean equals(Object obj)
-
判断当前这个对象和obj对象是不是相同
-
特性
- 自反性:对于任何非空的参考值
x
,x.equals(x
)应该返回true
- 对称性:对于任何非空引用值
x
和y
,x.equals(y)
返回true
当且仅当y.equeals(x)
返回true - 传递性:对于任何非空引用值
x
,y
和z
,如果x.equals(y)
回报true
和y.equals(z)
返回true
,然后x.equals(z)
应该返回true
- 一致性:对于任何非空引用值
x
和y
,多次调用x.equals(y)
始终返回true
或始终返回false
- 非空性:对于任何非空的参考值
x
,x.equals(null)
应该返回false
- 无论何时覆盖该方法,通常需要覆盖
hashCode
方法
- 自反性:对于任何非空的参考值
-
重写equals方法
5.finalize()方法
- 当对象被判定为垃圾对象时,由JVM自动调用此方法用以标记垃圾对象,进入回收队列。
- 垃圾对象:没有有效的引用指向此对象时,为垃圾对象
- 垃圾回收:由GC销毁垃圾对象,释放数据存储空间
- 自动回收机制:JVM的内存耗尽,一次性回收所有垃圾对象
- 手动回收机制:使用
System.gc()
;通知到JVM执行垃圾回收
重写finalize方法
new Student("aaa",20);
new Student("bbb",20);
new Student("ccc",20);
new Student("ddd",20);
System.gc();
三、包装类
-
基本数据类型所对应的引用数据类型,为了拥有属性和方法
-
包装类的默认值是null
-
基本数据类型 包装类型 byte Byte short Short int Integer long Long float Float double Double boolean Boolean char Character -
类型转换与装箱和拆箱
-
8种包装类提供不同类型间的转换方式
- Number()弗雷中提供的6个共性方法
- parsexxx()
- valueof()
- 装箱:把栈里面的数据放到堆里面,把基本类型转换成一个对象
- 拆箱:与装箱相反。 把引用类型转为基本类型
public class Demo1 {
public static void main(String[] args) {
//装箱
int num1 = 18;
Integer integer1 = new Integer(num1);
Integer integer2 = Integer.valueOf(num1);
System.out.println("========装箱=========");
System.out.println(integer1);
System.out.println(integer2);
//拆箱
Integer integer3 = new Integer(100);
int num2 = integer3.intValue();
System.out.println("==========拆箱==========");
System.out.println(num2);
/* 自动装箱 */
int age = 30;
Integer integer4 = age;
System.out.println("==========自动装箱==========");
System.out.println(integer4);
/* 自动拆箱 */
int age2 = integer4;
System.out.println("==========自动拆箱==========");
System.out.println(age2);
System.out.println("==========基本类型和字符串之间转换============");
System.out.println("----基本类型转字符串-----");
//基本类型和字符串之间转换
//1.基本类型转字符串
int n1 = 15;
// 1.1. 使用 +号
String s1 = n1+"";
// 1.2 使用Integer中的toString()方法 //f
String s2 = Integer.toString(n1,16);
System.out.println(s1);
System.out.println(s2);
System.out.println("----字符串转成基本类型-----");
//2.字符串转成基本类型
String str = "150";
//使用Integer.parsexxx();
int n2 = Integer.parseInt(str);
System.out.println(n2);
//boolean字符串转成基本类型 "true"--->true
String str2 = "true";
boolean b1 = Boolean.parseBoolean(str2);
System.out.println(b1);
}
}
整数缓冲区
- 自动装箱本质上也是利用valueOf方法
- valueOf是有范围的
public class Demo2 {
public static void main(String[] args) {
//面试题
Integer integer1 = new Integer(100);
Integer integer2 = new Integer(100);
System.out.println("使用new的方式,引用地址不同:" + (integer1 == integer2)); //false
System.out.println();
Integer integer3 = Integer.valueOf(100);
Integer integer4 = Integer.valueOf(100);
System.out.println("使用Integer.valueOf的方式,并且值在范围内:" + (integer3 == integer4)); //true
//自动装箱
//其实是有范围的 -128~127
//自动装箱本质上也就是利用valueOf方法
Integer integer5 = 100;
Integer integer6 = 100;
System.out.println();
System.out.println("在-128~127范围内:" + (integer5 == integer6)); //true
//自动装箱
//超出了范围
Integer integer7 = 200;
Integer integer8 = 200;
System.out.println();
System.out.println("不在-128~127范围内:" + (integer7 == integer8)); // false
}
}
四、String类
-
字符串是常量,创建不可改变
-
字符串字面值存储在**字符串池(在方法区 method area)**中,可以共享。
-
给字符串赋值的时候(如果之前没有),并没有修改之前的数据,而是重新开辟了一个新的空间,之前的数据就成了垃圾。
-
那为什么说是共享
-
String name = "zhangsan"; String name2 = "zhangsan"; 他们两个都指向同一个对象
-
-
创建方式:
-
String name = "zhangsan";
——产生一个对象,字符串池中存储; -
String name = new String("zhangsan");
——创建了两个对象 字符串池,堆 -
String name = new String("zhangsan"); String name2 = new String("zhangsan"); System.out.println(name == name2); //false System.out.println(name.equals(name2); //true //不同的对象,虽然这两个对象都指向同一字符串池中字符面值为"zhangsan"的一块区域.。 //如果用e.quals 是比较值,,就是true
-
-
常用方法:
-
字符串长度
public int length()
-
字符串某一个位置字符
-
public char charAt(int index)
-
String str = new String("helloworld"); char ch = str.charAt(4);//ch = o
-
-
查询下标
public int indexOf(String str)
public int indexOf(String str, int fromIndex)
- 查找str首次出现的下标,存在,则返回下标,不存在返回-1
public int lastIndexOf(String str)
- 查找str在当前字符串中最后一次出现的下标索引
-
提取
-
public String substring(int beginIndex)
- 从
beginInedex
开始,取出剩余字符串作为一个新字符串返回
- 从
-
public String substring(int beginIndex, int endIndex)
- 从
beginIndex
开始,到endIndex-1
位置的字符串作为返回结果
- 从
-
String str1 = newString("helloworld"); String str2 = str1.substring(2);//str2 ="lloworld" String str3 = str1.substring(2,5);//str3 ="llo"
-
-
比较
-
public int compareTo(String str)
-
该方法是对字符串内容按字典顺序进行大小比较
-
若当前对象比参数大则返回正整数,反之返回负整数,相等返回0
-
-
-
public int compareToIgnoreCase (String str)
- 忽略大小写
-
public boolean equals(Object obj)
- 比较当前字符串和参数字符串,在两个字符串相等的时候返回true,否则返回false
-
public boolean equalsIgnoreCase(String str)
- 忽略大小写
-
String str1 = new String("abc"); String str2 = new String("ABC"); String str3 = new String("abc1234") int a = str1.compareTo(str2);//a=32 比大小 int a2 = str1.compareTo(str3);//a2=4 这个时候比长度 int b = str1.compareToIgnoreCase(str2);//b=0 boolean c = str1.equals(str2);//c=false boolean d =str1.equalsIgnoreCase(str2);//d=true
-
-
连接
-
public String concat(String str)
- 将参数中的
字符串str
连接到当前字符串的后面,效果等价于+
- 将参数中的
-
String a = "hello"; a = a.concat("world"); // a = hellowolrd
-
-
大小写转换
public String toLowerCase()
- 返回将当前字符串中所有字符转换成小写后的新串
public String toUpperCase()
- 返回将当前字符串中所有字符转换成大写后的新串
-
替换
-
public String replace(char oldChar, charnewChar)
- 用字符串newChar替换当前字符串中所有的oldChar字符串,并返回一个新的字符串
-
public String replaceFirst(String regex,String replacement)
- 该方法用字符串replacement的内容替换当前字符串中遇到的第一个和字符串regex相匹配的子串,应将新的字符串返回
-
public String replaceAll(String regex,String replacement)
- 该方法用字符replacement的内容替换当前字符串中遇到的所有和字符串regex相匹配的子串,应将新的字符串返回。
-
String str = "helloworld"; String str1 = str.replace('h','g'); //str1 ="gelloworld" String str2 =str.replace("he","xxx"); //str2 = "xxxlloworld" String str3 =str.replaceFirst("l","w"); //str3 = "hewloworld" String str4 =str.replaceAll("l","w"); //str4 = "hewwoworwd" System.out.println(str1+"\n"+str2+"\n"+str3+"\n"+str4);
-
-
包含
public boolean contains(String s)
- 判断当前字符串中是否包含s
-
转换成数组
public char[] toCharArray()
- 将此字符串转换为新的字符数组
-
去空格
public String trim()
- 去掉两端空格
- 如果没有空格,返回自己。
-
分割
-
public String[] split(String regex)
——rege分隔正则表达式 -
String str = "boo:and:foo"; String[] str1 = str.split(":"); //String[] str1 = str.split(正则表达式); for (int i = 0; i < str1.length; i++) { System.out.println(str1[i]); //输出结果是boo and foo }
-
练习题:
public class Demo1 { public static void main(String[] args) { String str = "this is a text"; String[] arr = str.split(" "); System.out.println("------1.将str中的单词单独获取出来-----"); for (String s : arr) { if ("text".equals(s)){ System.out.println(s); } } System.out.println("------2.将str中的text替换为practice-----"); String result2 = str.replace("text","practice"); System.out.println(result2); System.out.println("------3.在text前面插入一个easy-----"); String result3 = str.replace("text","easy text"); System.out.println(result3); System.out.println("------4.将每个单词的首字母改为大写-----"); String news=""; for (int i = 0; i < arr.length; i++) { char first = arr[i].charAt(0); //把第一个字符转成大写 char uppfirst = Character.toUpperCase(first); news += uppfirst+arr[i].substring(1)+" "; } System.out.println(news); } }
-
可变字符串
**StringBuffer:**可变长字符串,JDK1.0提供,运行效率慢,线程安全。
**StringBuilder:**可变长字符串,JDK1.5提供,运行效率快,线程不安全。
比String快,节省内存
StringBuilder sb = new StringBuilder();
StingBuffer sf = new StringBuffer();
- append()
- insert()
- replace()
- delete()
五、BigDecimal类
public class Demo2 {
public static void main(String[] args) {
double d1 = 1.0;
double d2 = 0.9;
System.out.println(d1-d2);
double result = (1.4-0.5)/0.9;
System.out.println(result);
}
}
//0.09999999999999998
//0.9999999999999999
- double是近似值存储,而BigDecimal精度更大。
- 位置:java.math包中
- 作用:精确计算浮点数
- 创建方式:
BigDecimal bd = new BigDecimal("1.0");
使用字符串的形式
public class Demo2 {
public static void main(String[] args) {
double d1 = 1.0;
double d2 = 0.9;
System.out.println(d1-d2);
double result = (1.4-0.5)/0.9;
System.out.println(result);
BigDecimal db1 = new BigDecimal("1.0");
BigDecimal bd2 = new BigDecimal("0.9");
BigDecimal r1 = db1.subtract(bd2);
BigDecimal r2 = db1.add(bd2);
BigDecimal r3 = db1.multiply(bd2);
BigDecimal r4 = new BigDecimal("1.4")
.subtract(new BigDecimal("0.5"))
.divide(new BigDecimal("0.9"));
BigDecimal r5 = new BigDecimal("10").divide(new BigDecimal("3"),2,BigDecimal.ROUND_HALF_UP);
System.out.println("加法:"+r1);
System.out.println("减法:"+r2);
System.out.println("乘法:"+r3);
System.out.println("除法:"+r4);
System.out.println("除法:"+r5);
}
}
六、Date类
-
Date表示特定的瞬间,精确到毫秒。Date类中的大部分方法都已经被Calendar类中的方法所取代。
-
构造方法:
public Date(long date)
- date --1970年1月1日以来的毫秒数
public class Demo3 {
public static void main(String[] args) {
//1.创建Date对象
Date date1 = new Date();
Date date2 = new Date(3000121);
System.out.println(date1);
System.out.println(date1.toString());
System.out.println(date1.toLocaleString());
System.out.println(date2);
Date date3 = new Date(date1.getTime() - (60*60*24*1000));
System.out.println(date3.toString());
//2.方法 after before
boolean b1 = date1.after(date3);
boolean b2 = date1.before(date3);
System.out.println(b1);
System.out.println(b2);
//setTime
Date date4 = new Date();
date4.setTime(32132121);
System.out.println(date4.toString());
//compareTo
//date3是昨天,date1是今天, 昨天在前面,参数在后面,所以显示<0
int compareTo = date3.compareTo(date1);
System.out.println(compareTo);
//equals
boolean b3 = date1.equals(date2);
System.out.println(b3);
}
}
七、Calendar类
- Calendar类提供了获取和设置各种日历字段的办法
- 构造方法
- 其他方法
public class Demo4 {
public static void main(String[] args) {
//1.创建Calendar对象
System.out.println("------------1.创建Calendar对象--------------");
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTime().toLocaleString());
//2.获取时间信息
System.out.println("------------2.获取时间信息--------------");
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH); //0-11
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY); //HOUR是12小时, HOUR_OF_DAY 24小时
int minute = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
System.out.println(year+"年"+month+1+"月"+day+"日"+" "+hour+":"+minute+":"+seconds);
//修改时间
System.out.println("------------3.修改时间--------------");
Calendar calendar2 = Calendar.getInstance();
calendar2.set(Calendar.DAY_OF_MONTH,5);
System.out.println(calendar2.getTime().toLocaleString());
System.out.println(calendar2.getTime().toString());
//add方法修改时间
System.out.println("------------4.add方法修改时间--------------");
calendar2.add(Calendar.HOUR, -1);
System.out.println(calendar2.get(Calendar.HOUR));
System.out.println(calendar2.get(Calendar.HOUR_OF_DAY));
int max = calendar2.getActualMaximum(Calendar.DAY_OF_MONTH);
int min = calendar2.getActualMinimum(Calendar.DAY_OF_MONTH);
System.out.println(min);
System.out.println(max);
}
}
八、SimpleDateFormat类
-
SimpleDateFormat是一个以与语言环境有关的方式来格式化和解析日期的具体类
-
进行格式化(日期->文本)、解析(文本-> 日期)
-
常用的时间模式字母
-
字母 日期或时间 示例 y 年 M 年中月份 d 月中天数 H 1天中小时数(0~23) m 分钟 s 秒 S 毫秒
-
public class Demo5 {
public static void main(String[] args) throws Exception{
//1.创建SimpleDateFormat对象
//显示格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd");
//2.创建Date
Date date = new Date();
//格式化date
String str = sdf.format(date);
//2021年04月08日 22:43:41
System.out.println(str);
Date date2 = sdf2.parse("2020/09/24");
System.out.println(date2);
}
}
九、System类
- System系统类,主要用于获取系统的属性数据和其他操作,构造方法私有的。
System.arraycopy
复制数组System.currentTimeMillis()
获取当前系统时间,返回毫秒值System.gc()
建议JVM赶快启动垃圾回收器回收垃圾System.exit(0)
退出JVM,如果参数是0,表示正常退出JVM