Java常用类
目录
内部类
-
概念:在一个类内部再定义一个完整的类
成员内部类
-
在类的内部定义,与实例变量、实例方法同级别的类。
-
外部类的一个实例部分,创建内部类对象时,必须依赖外部类对象。
Outer outer = new Outer(); Outer.Inner inner = outer.new Inner();
-
当外部类、内部类存在重名属性时,会优先访问内部类属性。
public class Outer { private String name="tomyoung"; private int age=20; class Inner{ private String address="长沙"; private String phone="110"; private String name="李四"; public void show(){ //如果内部类和外部类属性重名,如何调用外部类属性 System.out.println(Outer.this.name);//外部类属性 System.out.println(this.age);//内部类属性 System.out.println(address); System.out.println(phone); } } }
-
成员内部类不能定义静态成员。
//Outer类
public class Outer {
private String name="tomyoung";
private int age=20;
class Inner{
private String address="长沙";
private String phone="110";
public void show(){
System.out.println(name);
System.out.println(age);
System.out.println(address);
System.out.println(phone);
}
}
}
//TestOUter类
public class TestOuter {
public static void main(String[] args) {
//1.创建外部类对象
Outer outer=new Outer();
//2.创建内部类对象
Outer.Inner inner=outer.new Inner();
//简化写法
Outer.Inner inner1=new Outer().new Inner();
inner.show();
System.out.println("==========================");
inner1.show();
}
}
/*
输出结果:
tomyoung
20
长沙
110
==========================
tomyoung
20
长沙
110
*/
静态内部类
-
不依赖外部类对象,可直接创建或通过类名访问,可声明静态成员。
-
只能直接访问外部类静态成员(实例成员需要实例化外部类对象)。
Outer.Inner inner = new Outer.Inner(); Outer.Inner.show();
//Outer02类
public class Outer02 {
private String name="tomyoung";
private int age=18;
//静态内部类,和外部类相同
static class Inner02{
private String address="长沙";
private String phone="111";
//静态成员
private static int count=1000;
public void show(){
//调用外部类属性
Outer02 outer02 = new Outer02();
System.out.println(outer02.age);
System.out.println(outer02.name);
//调用内部类属性
System.out.println(address);
System.out.println(phone);
//调用内部类静态属性
System.out.println(Inner02.count);
}
}
}
//TestOuter类
public class TestOuter {
public static void main(String[] args) {
//直接创建静态内部类对象
Outer02.Inner02 inner = new Outer02.Inner02();
//调用方法
inner.show();
}
}
/*
输出结果:
18
tomyoung
长沙
111
1000
*/
局部内部类
-
定义在外部类的方法中,作用范围和创建对象范围仅限于当前方法。
-
局部内部类访问外部类当前方法中局部变量时,因无法保障变量的生命周期与自身相同,变量必须修饰为final.
-
限制类的使用范围。
//Outer03类
public class Outer03 {
private String name="tomyoung";
private int age=20;
public void show(){
//定义局部变量
String address="csc";
//局部内部类,不能加任何访问修饰符
class Inner03{
private String phone="18573807102";
private String email="y000828@qq.com";
public void show2(){
//访问外部类属性
System.out.println(name);
System.out.println(age);
//访问内部类
System.out.println(phone);
System.out.println(email);
//访问局部变量
System.out.println(address);
}
}
Inner03 inner = new Inner03();
inner.show2();
}
}
//TestOuter类
public class TestOuter {
public static void main(String[] args) {
Outer03 outer = new Outer03();
outer.show();
}
}
/*
输出结果:
tomyoung
20
18573807102
y000828@qq.com
csc
*/
匿名内部类
-
没有类名的局部内部类(一切特征都与局部内部类相同。
-
必须继承一个父类或者实现一个接口。
-
定义类、实现类、创建对象的语法合并,只能创建一个该类的对象。
-
优点:减少代码量
-
缺点:可读性较差
-
//TestUsb类
public class TestUsb {
public static void main(String[] args) {
//使用匿名内部类(相当于创建一个局部内部类)
Usb usb=new Usb() {
@Override
public void service() {
System.out.println("连接成功,风扇开始工作了");
}
};
usb.service();
}
}
//Usb接口
public interface Usb {
void service();
}
Object类
-
超类、基类、所有类的直接或者间接父类,位于继承树的最顶层。
-
任何类、如没有书写extends显示继承某个类,都默认直接继承Object类,否则为间接继承。
-
Object类中所定义的方法,是所有对象都具备的方法。
-
Object类型可以存储任何对象。
-
作为参数,可接受任何对象。
-
作为返回值,可返回任何对象。
-
Object类常用方法
1.getClass()方法
-
public final Class<?> getClasss(){}
-
返回引用中存储的实际对象类型。
-
应用:通常用于判断两个引用中世纪存储对象类型是否一致。
//student类
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}
//Test类
public class Test {
public static void main(String[] args) {
Student stu = new Student("aaa",20);
Student stu2 = new Student("bbb",40);
//判断s1和s2是不是同一个类型
Class class1=stu.getClass();
Class class2=stu2.getClass();
if (class1==class2){
System.out.println("stu和stu2属于同一个类型");
}else {
System.out.println("stu和stu2不属于同一个类型");
}
}
}
/*
输出结果:
stu和stu2属于同一个类型
*/
2.hashCode()方法
-
public int hashCode(){}
-
返回该对象的哈希码值。
-
哈希值根据对象的地址或字符串或数字使用hash算法计算出来的int类的数值。
-
一般情况下相同对象返回相同的哈希码。
//Test类(Student类与上同)
public class Test {
public static void main(String[] args) {
Student stu = new Student("aaa",20);
Student stu2 = new Student("bbb",40);
//hashCode方法
System.out.println(stu.hashCode());
System.out.println(stu2.hashCode());
Student stu3=stu2;
System.out.println(stu3.hashCode());
}
}
/*
输出结果:
1163157884
1956725890
1956725890
*/
3.toString()方法
-
public String toString(){}
-
返回该对象的字符串表示(表现形式)
-
可以根据程序需求覆盖该方法,如:展示对象各个属性值。
//Student类
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
//重写toString方法
@Override
public String toString() {
return name+":"+age;
}
}
public class Test {
public static void main(String[] args) {
Student stu = new Student("aaa",20);
Student stu2 = new Student("bbb",40);
//toString方法
System.out.println(stu.toString());
System.out.println(stu2.toString());
}
}
/*
输出结果:
aaa:20
bbb:40
*/
4.equals()方法
-
public boolean equals(Object obj){}
-
默认实现为(this==obj),比较两个对象地址是否相同。
-
可进行覆盖,比较两个对象的内容是否相同。
equals()方法覆盖步骤
-
比较两个引用是否指向同一个地址
-
判断obj是否为null
-
判断两个引用指向的实际对象类型是否一致
-
强制类型转换
-
依次比较各个属性值是否相等
//Student类
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public boolean equals(Object obj) {
//1.判断两个对象是否为同一个
if (this==obj){
return true;
}
//2.判断obj是否为null
if (obj==null){
return false;
}
//3.判断是否为同一个类型
if(obj instanceof Student){
//4.强制类型转换
Student s=(Student)obj;
//5.比较属性
if (this.name.equals(s.getName())&&this.age==s.getAge()){
return true;
}
}
return false;
}
}
public class Test {
public static void main(String[] args) {
Student stu = new Student("aaa",20);
Student stu2 = new Student("bbb",40);
Student stu3=new Student("小明",17);
Student stu4=new Student("小明",17);
//equals方法
System.out.println(stu.equals(stu2));
System.out.println(stu3.equals(stu4));
}
}
/*
输出结果:
false
true
*/
5.finalize()方法
-
当对象被判定为垃圾对象时,由JVM自动调用次方法,用以标记垃圾对象,进入回收队列。
-
垃圾对象:没有有效引用指向此对象时,为垃圾对象。
-
垃圾回收:由GC销毁垃圾对象,释放数据存储空间。
-
自动回收机制:JVM的内存耗尽,一次性回收所有垃圾对象。
-
手动回收机制:是有System.gc();通知JVM执行垃圾回收。
//Student类
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
protected void finalize() throws Throwable {
System.out.println(this.name+"对象被回收");
}
}
//Test2类
public class Test2 {
public static void main(String[] args) {
new Student("aaa",1);
new Student("bbb",2);
new Student("ccc",3);
Student s4=new Student("ddd",4);
Student s5=new Student("eee",5);
//回收垃圾
System.gc();
System.out.println("回收垃圾");
}
}
/*
输出结果:
回收垃圾
ccc对象被回收
bbb对象被回收
aaa对象被回收
*/
包装类
-
基本数据类型所对应的引用数据类型。
-
Object可统一所有数据,包装类的默认值为null。
基本数据类型 包装类型 byte Byte short Short int Integer long Long float Float double Double boolean Boolean char Character
1.类型转换与装箱、拆箱
-
八种包装类提供不同类型间的转换方式:
-
Number父类中提供6个共性方式。
-
parse XXX()静态方法。
-
valueOf()静态方法。
-
-
注意⚠️:需保证类型兼容,否则抛出Number Format Exception异常。
public class Demo01 {
public static void main(String[] args) {
//类型转换:装箱,基本类型转成引用类型的过程
//基本类型
int num1=10;
//使用Integer类创建对象
Integer integer = new Integer(num1);
Integer integer2 =Integer.valueOf(num1);
//类型转换:拆箱引用类型转基本类型
Integer integer3=new Integer(100);
int num2=integer3.intValue();
System.out.println(integer);
System.out.println(integer2);
System.out.println(num2);
System.out.println("=========================");
//JDK1.5之后,提供自动装箱的拆箱
int age=30;
//自动装箱
Integer integer4=age;
//自动拆箱
int age2=integer4;
System.out.println(integer4);
System.out.println(age2);
}
}
/*
输出结果:
10
10
100
=========================
30
30
*/
public class Demo02 {
public static void main(String[] args) {
//基本类型和字符串之间的转换
//1基本类型转换成字符串
int n1=15;
//1.1使用+号
String s1=n1+"";
//1.2Integer中静态方法
String s2=Integer.toString(n1,16);//把n1转换成16进制
System.out.println(s1);
System.out.println(s2);
//2字符串转换成基本类型
String str="150";
//使用Integer.parseXXX();
int n2=Integer.parseInt(str);
System.out.println(n2);
//boolean类型字符串转成基本类型,"true"--->true 非"ture"--->false
String str2="a";
boolean b1=Boolean.parseBoolean(str2);
System.out.println(b1);
}
}
/*
输出结果:
15
f
150
false
*/
2.整数缓冲区
-
Java预先创建了256个常用的整数包装类型对象
public class Demo03 {
public static void main(String[] args) {
//面试题
Integer integer=new Integer(100);
Integer integer2=new Integer(100);
System.out.println(integer==integer2);
Integer integer3=100;//自动装箱,在缓冲区(-127-126则在堆一个地址,方便复用,减少内存空间)
Integer integer4=100;
System.out.println(integer3==integer4);
Integer integer5=200;//自动装箱
Integer integer6=200;
System.out.println(integer5==integer6);
}
}
/*
输出结果:
false
true
false
*/
String类
-
字符串是常量,创建之后不可以改变。
-
字符串字面值存储在字符串池当中,可以共享。(JDK8之前在方法区中,之后在堆中)
-
String s="hello";产生一个对象,字符串池中存储。
-
String s= new String("hello");//产生两个对象,堆、池各存储一个。
public class Demo04 {
public static void main(String[] args) {
String name="hello";//"hello"常量存储在字符串池中
name="张三";//给字符串赋值时,不是修改数据,而是重新开辟空间(不可变性)
String name2="张三";//实现共享
//字符串的另一种创建方式,new String()
String str=new String("java");
String str2=new String("java");
System.out.println(str==str2);
}
}
/*
输出结果:
true
*/
1.常用方法
-
public int length():放回字符串的长度。
-
public char charAt(int index):根据下标获取字符。
-
public boolean contains(String str):判断当前字符串中是否包含str。
-
public char[] toCharArray():将字符串转换成数组。
-
public int indexOf(String str):查找str首次出现的下标,存在,则返回下标;不存在,则返回-1.
-
public int lastindexOf(String str):查找str最后一次出现在字符串的下标索引。
-
public String trim():去掉字符串前后的空格。
-
public String tpUpperCase():将小写转成大写。
-
public boolean endWith(String str):判断字符串是否以str结尾。
-
public String replace(char oldChar,char newChar):将旧字符替换成新字符串。
-
public String[] split(String str):根据str做拆分。
import java.util.Arrays; public class Demo05 { public static void main(String[] args) { //字符串中常用方法的使用 String content="java是世界上最好的编程语言"; String content2=" Hello World "; String content3="Hello.java"; //1.length() System.out.println(content.length()); //2.charAt(int index) System.out.println(content.charAt(5)); //3.contains(String str) System.out.println(content.contains("java")); //4.toCharArray() System.out.println(Arrays.toString(content.toCharArray())); //5.indexOf(String str) System.out.println(content.indexOf("java")); System.out.println(content.indexOf("java",4));//从下标为4开始查找 //6.lastindexOf(String str) System.out.println(content.lastIndexOf("语言")); //7.trim() System.out.println(content2.trim()); //8.tpUpperCase()//toLowerCase() System.out.println(content2.toUpperCase()); System.out.println(content2.toLowerCase()); //9.endWith(String str)//startWith(String str) System.out.println(content3.startsWith("Hiello")); System.out.println(content3.endsWith("java")); //10.replace(char oldChar,char newChar) System.out.println(content.replace("java","php")); //11.split(String str) String say="java is the best oop language,java hello"; String[] arr=say.split("[ ,]+"); System.out.println(arr.length); for(String string : arr){ System.out.println(string); } //12.补充两个方法equals、compareTo():比较大小 String s1="hello"; String s2="HELLO"; System.out.println(s1.equals(s2)); System.out.println(s1.equalsIgnoreCase(s2)); String s3="abc"; String s4="xyz"; System.out.println(s3.compareTo(s4)); String s5="abc"; String s6="abcxyz"; System.out.println(s5.compareTo(s6)); } } /* 输出结果: 15 世 true [j, a, v, a, 是, 世, 界, 上, 最, 好, 的, 编, 程, 语, 言] 0 -1 13 Hello World HELLO WORLD hello world false true php是世界上最好的编程语言 8 java is the best oop language java hello false true -23 -3 */
2.案例
-
需求:
-
已知String str = "this is a text";
-
将str中的单词单独获取出来
-
将str中的text替换为practice
-
在text前面插入一个easy
-
将每个单词的首字母改为大写
-
import java.util.Arrays;
public class Demo06 {
public static void main(String[] args) {
String str = "this is a text";
String[] arr=str.split(" ");
for(String string:arr){
System.out.println(string);
}
String[] arr2=new String[arr.length];
System.out.println(str.replace("text","practice"));
System.out.println(str.replace("text","easy text"));
for(int i=0;i<arr.length;i++){
char first=arr[i].charAt(0);
char upperfirst = Character.toUpperCase(first);
String news=upperfirst+arr[i].substring(1);
System.out.println(news);
arr2[i]=news;
}
System.out.println(Arrays.toString(arr2));
}
}
/*
输出结果:
this
is
a
text
this is a practice
this is a easy text
This
Is
A
Text
[This, Is, A, Text]
*/
3.可变字符串
-
StringBuffer:可变长字符串,JDK1.0提供,运行效率慢、线程安全。
-
StringBuilder:可变长字符串,JDK5.0提供,运行效率快,线程不安全。
/**
* StringBuffer和StringBuilder的使用
* 和String区别(1)效率比String高(2)比String省内存
*/
public class Demo07 {
public static void main(String[] args) {
//StringBuilder和StringBuffer方法相同
StringBuffer sb=new StringBuffer();
//1.append();追加
sb.append("java世界第一");
System.out.println(sb.toString());
sb.append("java真香");
System.out.println(sb.toString());
//2.insert();添加
sb.insert(0,"我在最前面");
//3.replace();
sb.replace(0,5,"hello");
System.out.println(sb.toString());
//4.delete();删除
sb.delete(0,5);
System.out.println(sb.toString());
}
}
/*
输出结果:
java世界第一
java世界第一java真香
hellojava世界第一java真香
java世界第一java真香
*/
/**
* 验证StringBuilder效率高于String
*/
public class Demo08 {
public static void main(String[] args) {
long start=System.currentTimeMillis();
String string="";
for(int i=0;i<99999;i++){
string+=i;
}
long end=System.currentTimeMillis();
System.out.println("用时"+(end-start));
}
}
/*
输出结果:
1676
*/
/**
* 验证StringBuilder效率高于String
*/
public class Demo08 {
public static void main(String[] args) {
long start=System.currentTimeMillis();
StringBuilder sb=new StringBuilder();
for(int i=0;i<99999;i++){
sb.append(i);
}
long end=System.currentTimeMillis();
System.out.println("用时"+(end-start));
}
}
/*
输出结果:
17
*/
BigDecimal类
-
思考:以下程序输出结果是多少?
public claass TestBigDecimal{ public static void main(String[] args){ double d1=1.0; double d2=0.9; System.out.println(d1-d2); } }
-
结果为0.09999999999999998
-
-
原因:double是近似值存储,存在误差(即使很小,在一些实际生活中,也不可接受,如银行问题)
-
位置:java.math包中。
-
作用:精确计算浮点数。
-
创建方式:BigDecimal bd=new BigDecimal("1.0");
import java.math.BigDecimal;
public class Demo09 {
public static void main(String[] args) {
double d1=1.0;
double d2=0.9;
System.out.println(d1-d2);
//BigDecimal,大的浮点数精确计算
BigDecimal bd=new BigDecimal("1.0");
BigDecimal bd2=new BigDecimal("0.5");
//substract减法
BigDecimal a1=bd.subtract(bd2);
System.out.println(a1);
//add加法
BigDecimal a2=bd.add(bd2);
System.out.println(a2);
//multiply乘法
BigDecimal a3=bd.multiply(bd2);
System.out.println(a3);
//divide除法
BigDecimal a4=bd.divide(bd2);
System.out.println(a4);
//链式编程
BigDecimal a5=new BigDecimal("1.4")
.subtract(new BigDecimal("0.5"))
.divide(new BigDecimal("0.9"));
System.out.println(a5);
BigDecimal a6=new BigDecimal("1")
.divide(new BigDecimal("0.3"),2,BigDecimal.ROUND_HALF_UP);//除不尽要说明保留几位小数,ROUND_HALF_Up四舍五入
System.out.println(a6);
}
}
/*
输出结果:
0.09999999999999998
0.5
1.5
0.50
2
1
3.33
*/
Date类
-
Date表示特定的瞬间,精确到毫秒。Date类中的大部分方法都已被Calendar类中的方法所取代。
-
时间单位
-
1秒=1000毫秒
-
1毫秒=1000微秒
-
1微秒=1000纳秒
-
import java.util.Date;
public class Demo10 {
public static void main(String[] args) {
Date d1=new Date();
System.out.println(d1.toString());
System.out.println(d1.toLocaleString());//过时
Date d2=new Date(d1.getTime()-60*60*24*1000);
System.out.println(d2.toLocaleString());
//1.方法after/before
System.out.println(d1.after(d2));
System.out.println(d1.before(d2));
//2.方法compareTo();
System.out.println(d1.compareTo(d2));
System.out.println(d2.compareTo(d1));
//3.方法equals()
System.out.println(d1.equals(d2));
}
}
/*
输出结果:
Thu Sep 09 13:59:18 CST 2021
2021-9-9 13:59:18
2021-9-8 13:59:18
true
false
1
-1
false
*/
Calendar类
-
Calendar提提供了获取或设置各种日历字段的方法。
-
构造方法:
-
protected Calendar():由于修饰符是protected,所以无法直接创建该对象。
-
-
其他方法:
-
static Calendar getInstance():使用默认时区和区域获取日历。
-
void set(int year,int month,int date,int hourofday,int minute,int second):设置日历的年、月、日、时、分、秒
-
int get(int field):返回给定日历字段的值。字段比如年、月、日等。
-
void setTime(Date date):用给定的Date设置此日历的时间。Date- Calendar
-
Date getTime():返回一个Date表示此日历的时间。Calendar- Date
-
void add(int field,int amount):按照日历的规则,给指定字段添加或减少时间量
-
long getTimeInMilliesss():毫秒为单位返回该日历的时间值
-
import java.util.Calendar;
public class Demo11 {
public static void main(String[] args) {
//1.创建Calenda对象
Calendar calendar=Calendar.getInstance();
System.out.println(calendar.getTime().toLocaleString());
//2.获取时间信息
//获取年
int year=calendar.get(calendar.YEAR);
//获取月
int month=calendar.get(calendar.MONTH);
//获取日
int day=calendar.get(calendar.DAY_OF_MONTH);
//获取具体小时
int hour=calendar.get(calendar.HOUR_OF_DAY);//HOUR12小时,HOUR_OF_DATY24小时
//获取分钟
int minute=calendar.get(calendar.MINUTE);
//获取秒
int second=calendar.get(calendar.SECOND);
System.out.println(year+"年"+(month+1)+"月"+day+"日"+hour+"时"+minute+"分"+second+"秒");
//3.修改时间
Calendar calendar2=Calendar.getInstance();
calendar2.set(Calendar.DAY_OF_MONTH,14);
System.out.println(calendar2.getTime().toLocaleString());
//4.add方法修改时间
calendar2.add(Calendar.HOUR,1);
System.out.println(calendar2.getTime().toLocaleString());
//5.补充方法
int max=calendar2
.getActualMaximum(Calendar.DAY_OF_MONTH);
int max2=calendar2
.getActualMinimum(Calendar.DAY_OF_MONTH);
System.out.println(max);
System.out.println(max2);
}
}
/*
输出结果:
2021-9-15 15:17:47
2021年9月15日15时17分47秒
2021-9-14 15:17:47
2021-9-14 16:17:47
30
1
*/
SimpleDateFormat
-
SimpleDateFormat是一个以与语言环境有关的方式来格式化和解析日期的具体类。
-
进行格式化(日期->文本)、解析(文本->日期)
-
常用的时间模式字母
字母 日期或时间 示例 y 年 2019 M 年中月份 08 d 月中天数 10 H 一天中的小时数(0-23) 22 m 分钟 16 s 秒 59 S 毫秒 367
import java.text.SimpleDateFormat;
import java.util.Date;
public class Demo12 {
public static void main(String[] args) throws Exception{
//1.创建一个SimpleDAteFormat对象
SimpleDateFormat adf=new SimpleDateFormat("yyyy/MM/dd");
//2.创建一个Date
Date date=new Date();
//格式化date
String str=adf.format(date);
System.out.println(str);
//解析
Date date2=adf.parse("2021/08/28");
System.out.println(date2);
}
}
/*
输出结果:
2021/09/15
Sat Aug 28 00:00:00 CST 2021
*/
System类
-
System系统类,主要用于获取系统属性数据和其他操作,构造方法私有的。
-
方法名 说明 static void array copy(...) 复制数组 static long currentTimeMills(); 获取当前系统时间,返回的是毫秒值 static void gc(); 建议JVM赶快启动垃圾回收器回收垃圾 static void exit(int status) 推出JVM,如果参数是0表示正常退出,非0则表示异常退出JVM
import java.util.Arrays;
public class Demo13 {
public static void main(String[] args) {
//1.arraycopy:数组复制
//参数1:src,原数组
//参数2:srcPos,从哪个位置开始复制
//参数3:dest,目标数组
//参数4,destPos,目标数组的位置
//参数5:length,复制的长度
int[] arr={20,18,15,8,35,26,45,90};
int[] dest=new int[8];
System.arraycopy(arr,1,dest,0,4);
for(int j:dest){
System.out.println(j);
}
//2.获取毫秒数
System.out.println(System.currentTimeMillis());
long start =System.currentTimeMillis();
for(int i=0;i<999999;i++){
for(int j=1;j<99999;j++);
}
long end=System.currentTimeMillis();
System.out.println(end-start);
//3.退出JVM
System.exit(0);
System.out.println("程序结束了");//不会执行这一段,在上一个exit就已经结束
}
}
/*
输出结果:
18
15
8
35
0
0
0
0
1631780733162
6
*/