常用类
内部类
Object类
- 超类、基类,所有类的之间或简介父亲,位于继承树的最顶层。
- 任何类,如没有书写extends显示继承某个类,都默认直接继承Object类,否则为间接继承。
- Object类中所定义的方法,是所有对象都具备的方法。
- Object类型可以存储任何对象。
- 作为参数,可接受任何对象;
- 作为返回值,可返回任何对象。
getClass()方法
- public final Class< > getClass(){ }
- 返回引用中存储的实际对象类型
- 应用:通常用于判断两个引用中实际存储对象类型是否一致
package com.uvw.exception.demo6;
public class Student {
private String name;
private int age;
//构造方法
public Student(){
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
//get set方法
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;
}
}
package com.uvw.exception.demo6;
public class Test{
public static void main(String[] args) {
Student s1 = new Student("aa",11);
Student s2 = new Student("bb",31);
//判断class1和class2是不是一个类型
Class class1 = s1.getClass();
Class class2 = s2.getClass();
if (class1==class2){
System.out.println("是同一类型");
}else{
System.out.println("不是同一类型");
}
}
}
hashCode()方法
- publiic int hashCode(){ }
- 返回该对象的哈希码值
- 哈希码值根据对象的地址或字符串或数字使用hash算法计算出来的int类型的数值。
- 一般情况下相同对象返回相同哈希码
//hashCode方法
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
Student s3 = s1;
System.out.println(s3.hashCode());
//结果:356573597
// 1735600054
// 356573597
to String()方法
- public String toString(){ }
- 返回该对象的字符串表示(表现形式)
System.out.println(s1.toString());
System.out.println(s2.toString());
//结果:com.uvw.exception.demo6.Student@1540e19d
//com.uvw.exception.demo6.Student@677327b6
- 可以根据程序需求覆盖该方法,如:展示对象各个属性值。
//toString的重写 Alt+Insert-->toString
@Override
public String toString() {
return "Student{" + "name='" + name + '\'' + ", age=" + age + '}';
}
//运行结果:Student{name='aa', age=11}
//Student{name='bb', age=31}
equals()方法
- public Boolean equals(Object obj){ }
- 默认实现为(this == obj),比较两个对象地址是否相同。
System.out.println(s1.equals(s2));//false
Student s4 = new Student("小米",12);
Student s5 = new Student("小米",12);
System.out.println(s4.equals(s5));//false,因为地址不同
- 可进行覆盖,比较两个对象的内容是否相同。
equals()方法覆盖步骤
- 比较两个引用是否指向同一个对象
- 判断 obj 是否为 null
- 判断两个引用指向的实际对象类型是否一致
- 依次比较各个属性值是否相同。
@Override
public boolean equals(Object obj) {
//1.判断两个对象是否是同一个引用
if (this==obj){
return true;
}
//2.判断obj是否null
if (obj==null){
return false;
}
//3.判断是否是同一个类型
// if (this.getClass()==obj.getClass()){
// }
//instanceof 判断对象是否是某种类型
if(obj instanceof Student){
//4.强制转换对象
Student s = (Student)obj;
//5.比较属性
if (this.name.equals(s.getName())&&this.age==s.getAge()){
return true;
}
}
return false;
}
finalize()方法
- 当对象被判定为垃圾对象时,由 JVM 自动调用此方法,用以标记垃圾对象,进入回收队列。
- 垃圾对象:没有有效引用指向此对象时,为垃圾对象。
- 垃圾回收:由GC销毁垃圾对象,释放数据存储空间。
- 自动回收机制:JVM 的内存耗尽,一次性回所有垃圾对象。
- 手动回收机制:使用System.gc() ; 通知 JVM 执行垃圾回收。
@Override
protected void finalize() throws Throwable {
System.out.println(this.name+"对象被回收了");
}
package com.uvw.exception.demo6;
import javax.swing.text.Style;
public class Test2 {
public static void main(String[] args) {
//abc是垃圾
new Student("a",20);
new Student("b",20);
new Student("c",20);
Student s4 = new Student("d",20);
Student s5 = new Student("e",20);
//回收垃圾
System.gc();
System.out.println("回收垃圾");
}
}
包装类
- 基本数据类型所对应的引用数据类型
- object可统一所有数据,包装类的默认值是null
包装类型 | 基本数据类型 |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
boolean | Boolean |
char | Character |
类型转换与装箱、拆箱
-
8种包装类 提供不同类型间的转换方式:
-
Number父类中提供的6个共性方法。
-
valueOf()静态方法
package com.uvw.exception.demo7; public class A { public static void main(String[] args) { //int num=0; //类型转换:装箱,基本类型转成引用类型的过程 //基本类型 int num1=18; //使用Integer类创建对象 Integer integer1 = new Integer(num1); Integer integer2 =Integer.valueOf(num1);//valueOf()静态方法 System.out.println(integer1); System.out.println(integer2); //类型转型:拆箱,引用类型转成基本类型 Integer integer3 = new Integer(100); int num2=integer3.intValue(); System.out.println("---拆箱---"); System.out.println(num2); //JDK1.5之后,提供自动装箱和拆箱,调用Integer.valueOf() int age=30; //自动装箱 Integer integer4=age; System.out.println("--自动装箱--"); System.out.println(integer4); //自动拆箱 int age2=integer4; System.out.println("--自动拆箱--"); System.out.println(age2); } }
-
基本类型和字符串之间的转换
- parseXXX( )静态方法
package com.uvw.exception.demo7;
public class B {
public static void main(String[] args) {
//基本类型和字符串之间转换
//1.基本类型转换成字符串
int n1 = 15;
//方法a.使用符号 +
String s1 = n1 + "";
//方法b.使用Integer中的toString()方法
String s2 = Integer.toString(n1,16);//转成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 非 ”true“-->false
String str2="false";
boolean b1=Boolean.parseBoolean(str2);
System.out.println(b1);
}
}
注意:需保证类型兼容,否则抛出NumberFormatException异常。
整数(Integer)缓冲区
-
Java 预先创建了256个常用的整数包装类型对象。
-
由以上代码可知,缓冲区范围:-128<= i <=127,从缓冲区获取,若不在范围内,就new一。
package com.uvw.exception.demo7;
public class C {
public static void main(String[] args) {
Integer integer1 = new Integer(100);
Integer integer2 = new Integer(100);
System.out.println(integer1==integer2);//false
// 因为引用类型地址不同
Integer integer3=100;//自动装箱
Integer integer4=100;
System.out.println(integer3==integer4);//true
//因为在缓冲区范围内,直接从缓冲区获取”100“
Integer integer5=200;
Integer integer6=200;
System.out.println(integer5==integer6);//false
//因为超出了缓冲区范围
}
}
String概述
String类
- 字符串是常量,创建之后不可改变。
- 字符串字面值存储在字符串池中(字符串池在方法区中),可以共享。
package com.uvw.exception.demo8;
public class StringDemo1 {
public static void main(String[] args) {
String name = "hello";//"hello"常量存储在字符串池中
name = "WTianTian";//"WTianTian"赋值给name变量,
// 给字符串赋值时,并没有修改数据,而是重新开始
String name2 = "WTianTian";
}
}
- 方法1:产生一个对象,在字符串池中存储。String s = “hello”;
- 方法2:产生两个对象,堆、池各存储一个。String s = new String(“hello”);
package com.uvw.exception.demo8;
public class StringDemo1 {
public static void main(String[] args) {
String name = "hello";//"hello"常量存储在字符串池中
name = "zhangsan";//"zhangsan"赋值给name变量,
// 给字符串赋值时,并没有修改数据,而是重新开始
String name2 = "WTianTian";
//演示字符串的另一种创建方式,new String();
//会产生两个对象,造成空间浪费
String str1 = new String("java");
String str2 = new String("java");
System.out.println(str1==str2);//false
System.out.println(str1.equals(str2));//true
//equals是判断两个变量或者实例指向同一个内存空间的值是不是相同;
//而==是判断两个变量或者实例是不是指向同一个内存空间;
//举个通俗的例子来说,==是判断两个人是不是住在同一个地址,而equals是判断同一个地址里住的人是不是同一个。
}
}
String常用方法
- 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):查找字符串在当前字符串中最后一次出现的下标索引。
- public String trim():去掉字符串前后的空格。
- public String toUpperCase():将小写转成大写。toLowerCase();把大写转成小写。
- public boolean endWith(String str):判断字符串是否以str结尾。startWith(str);判断是否以str开头。
- public String replace(char oldChar,char newChar);将旧字符串替换成新字符串。
- public String[] split(Stirng str):根据str做拆分。
package com.uvw.exception.demo8;
import com.uvw.scanner.Array;
import java.util.Arrays;
public class StringDemo2 {
public static void main(String[] args) {
//字符串方法的使用
//1.length();返回字符串的长度
//2.charAt(int index);返回某个位置的字符
//3.contains(String str);判断是否包含某个字符串
System.out.println("-------字符串方法的使用1-----");
String content="java语言java是最好的java妙";
System.out.println(content.length());
System.out.println(content.charAt(content.length()-1));
System.out.println(content.contains("java"));
System.out.println(content.contains("php"));
System.out.println("-------字符串方法的使用2-----");
//4.toCharArray();返回字符串对应的数组
//5.indexOf();返回子字符串首次出现的位置
//6.lastIndexOf();返回字符串最后一次出现的位置
System.out.println(Arrays.toString(content.toCharArray()));
System.out.println(content.indexOf("java"));
System.out.println(content.indexOf("java",4));
System.out.println(content.lastIndexOf("java"));
System.out.println("------字符串方法的使用3------");
//7.trim();去掉字符串前后的空格
//8.toUpperCase();把小写转成大写,toLowerCase();把大写转成小写
//9.endWith(str);判断是否以str结尾,startsWith(str);判断是否以str开头
String content2=" hello WORLD ";
System.out.println(content2.trim());
System.out.println(content2.toUpperCase());
System.out.println(content2.toLowerCase());
System.out.println(content2.endsWith(" "));
System.out.println(content2.startsWith(" "));
System.out.println(content2.startsWith("h"));
System.out.println("------字符串方法的使用4------");
//10.replace(char old,char new);用新的字符串替换旧的字符或字符串
//11.split();对字符串进行拆分
System.out.println(content.replace("java","php"));
String say="java is the best programing language, I love java";
String[] arr=say.split("[ ,]+");//允许出现多个空格和逗号
System.out.println(arr.length);
for (String string:arr){
System.out.println(string);
}
}
}
案例
package com.uvw.exception.demo8;
public class Test {
public static void main(String[] args) {
String str="this is a text";
//1.将str中的单词单独获取出来
String[] arr=str.split(" ");
for (String s:arr){
System.out.println(s);
}
//2.将str中的text替换为practice
System.out.println(str.replace("text","practice"));
//3.在text前面插入一个easy
System.out.println(str.replace("text","easy text"));
//4.将每个单词的首字母改为大写
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.print(news+" ");
}
}
补充equals、compareTo
//补充两个方法:equals、compareTo();比较大小
String s1="hello";
String s2="HELLO";
System.out.println(s1.equalsIgnoreCase(s2));//不区分大小写,比较是否相等
String s3="abc";//a=97
String s4="xyz";//x=120
System.out.println(s3.compareTo(s4));//-23
//若第一个字母不同,ASCII码中对应的值相减;若相同继续对比下一个字母.
String s5=" abc";
String s6="abcxyz";
System.out.println(s5.compareTo(s6));//-3
//比较字符长度,s5-s6
可变字符串
- StringBuffer:可变长字符串,JDK1.0提供,运行效率慢、线程安全。
- StringBuilder:可变长字符串,JDK5.0提供,运行效率快、线程不安全。
StringBuffer和String的区别:1.效率比 String 高;2.比String节省内存。
package com.uvw.exception.demo8;
public class StringBufferDemo {
public static void main(String[] args) {
StringBuffer sb=new StringBuffer();
//1.append();追加
sb.append("java1111");
System.out.println(sb.toString());
sb.append("java2222");
System.out.println(sb.toString());
sb.append("java3333");
System.out.println(sb.toString());
//2.insert();添加
sb.insert(0,"我在最前面");
System.out.println(sb.toString());
//3.replace();替换
sb.replace(0,3,"hello");
System.out.println(sb.toString());
//4.delete();删除
sb.delete(0,5);
System.out.println(sb.toString());
//清空
sb.delete(0,sb.length());
System.out.println(sb.length());
}
}
BigDecimal
-
位置:java.math包中
-
作用:精确计算浮点数
-
创建方式:BigDecimal bd=new BigDecimal(“1.0”);
-
除法:divide(BigDecimal bd,int scal,RoundingMode mode)
参数scal:指定精确到小数点后几位
参数mode:指定小数部分的取舍模式,通常采用四舍五入的模式,取值为BigDecimal.ROUND_HELF_UP。
-
package com.uvw.exception.demo9; import com.uvw.oop.demo3.B; import java.math.BigDecimal; public class BigDecimalDemo { public static void main(String[] args) { double d1 = 1.0; double d2 = 0.9; System.out.println(d1-d2); //BigDecimal,大的浮点数精确计算 BigDecimal bd1 = new BigDecimal("1.0"); BigDecimal bd2 = new BigDecimal("0.9"); //减法 BigDecimal result1 = bd1.subtract(bd2);//bd1-bd2 System.out.println(result1); //加法 BigDecimal result2 = bd1.add(bd2); System.out.println(result2); //乘法 BigDecimal result3 = bd1.multiply(bd2); System.out.println(result3); //除法 (1.4-0.5)/0.9 BigDecimal result4 = new BigDecimal(1.4) .subtract(new BigDecimal(0.5)) .divide(new BigDecimal(0.9), 1, BigDecimal.ROUND_HALF_UP); //定义小数点后一位,JAVA中用BigDecimal做除法的时候一定要在divide方法中传 // 递第二个参数,定义精确到小数点后几位,否则在不整除的情况下,结果是无限 // 循环小数时,就会抛出异常。 System.out.println(result4); } }
Date类
-
Date表示特定的瞬间,精确到毫秒。Date类中的大部分方法都已经被类中的方法所取代。
-
时间单位 :1秒=1000毫秒,1毫秒=1000毫秒,1微秒=1000纳秒
package com.uvw.exception.demo9; import java.util.Date; public class DateDemo { public static void main(String[] args) { //1.创建Date对象 //今天 Date d1 = new Date(); System.out.println(d1.toString()); System.out.println(d1.toLocaleString());//方法过时了 //昨天 Date d2 = new Date(d1.getTime()-(60*60*24*1000));//1970.1.1到今天减去一天的毫秒数 System.out.println(d2.toLocaleString()); //2.方法 after before boolean b1 = d1.after(d2);//今天在昨天之后 System.out.println(b1);//T boolean b2 = d2.before(d2);//昨天在昨天之前 System.out.println(b2);//F //比较 compareTo(); 得到正数负数或零 int d = d2.compareTo(d1); System.out.println(d); //比较是否相等 equals() boolean b3 = d1.equals(d2); System.out.println(b3);
Calendar类
-
Calendar提供了获取或设置各种日历字段的方法。
-
构造方法 protected Calendar( ):由于修饰符是protected,所以无法直接创建该对象。
-
其他方法
package com.uvw.exception.demo9;
import java.util.Calendar;
public class CalendarDemo {
public static void main(String[] args) {
//1.创建Calendar对象
Calendar calendar=Calendar.getInstance();
System.out.println(calendar.getTime().toLocaleString());
System.out.println(calendar.getTimeInMillis());
//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);
//分钟
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,5);
System.out.println(calendar2.getTime().toLocaleString());
//4.add方法修改时间
calendar2.add(Calendar.HOUR,-1);
System.out.println(calendar2.getTime().toLocaleString());
//5.getActualMaximum方法
calendar2.add(Calendar.MONTH,1);//下个月,要查找本月天数就删除这行代码
int max=calendar2.getActualMaximum(Calendar.DAY_OF_MONTH);
int min=calendar2.getActualMinimum(Calendar.DAY_OF_MONTH);
System.out.println(max);//一个月有多少天
System.out.println(min);
}
}
SimpleDateFormat类
-
SimpleDateFormat是一个以 与语言环境有关的方式来格式化和解析日期的具体类。
-
进行格式化(日期–>文本)、解析(文本–>日期)。
-
常用的时间模式字母
package com.uvw.exception.demo9; import java.text.SimpleDateFormat; import java.util.Date; public class SimpleDFDemo { public static void main(String[] args) throws Exception{ //1.创建SimpleDateFormat对象 Y年 M月 SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH-mm-ss"); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //2.创建Date Date date = new Date(); //3.格式化date(把日期转换成字符串) String str = sdf.format(date); String str1 = sdf1.format(date); System.out.println(str);//2021/01/09 16-20-53 System.out.println(str1);//2021-01-09 16:20:53 //解析(把字符串转换成日期) Date date2 = sdf.parse("1990/05/01 21-22-22"); System.out.println(date2); } }
System类
- System系统类,主要用于获取系统的属性数据和其它操作,构造方法私有的。
package com.uvw.exception.demo9;
public class SystemDemo {
public static void main(String[] args) {
//1. arraycopy:数组的复制
//src:源数组。srcPos:从那个位置开始复制,第一个位置是0
//dest:目标数组。destPos:目标数组的位置。length:复制的长度
int[] arr={20,13,24,4,65,77,2,99};
int[] dest=new int[8 ];
System.arraycopy(arr,4,dest,4,4);
for (int i = 0; i < dest.length; i++) {
System.out.print(dest[i]+" ");
}
//也可以用 Array.copyof(original,newLength)
//2.获取毫秒数
System.out.println(System.currentTimeMillis());
long start=System.currentTimeMillis();
for (int i = -999999; i < 999999; i++) {
for (int j = -999999; j < 999999; j++) {
int result = i+j;
}
}
long end = System.currentTimeMillis();
System.out.println("用时:"+(end-start));
//3. System.gc();告诉垃圾回收器回收
//垃圾对象
new GCDemo("a",19);
new GCDemo("b",19);
new GCDemo("c",19);
//非垃圾对象
GCDemo g1 = new GCDemo("aa",19);
GCDemo g2 = new GCDemo("bb",19);
GCDemo g3 = new GCDemo("cc",19);
System.gc();
//4.退出JVM
System.exit(0);//结果显示 0说明退出成功
System.out.println("程序结束了");
}
}
3.垃圾回收 要额外创建一个类
package com.uvw.exception.demo9;
public class GCDemo extends SystemDemo{
private String name;
private int age;
public GCDemo(String name, int age) {
super();
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 String toString() {
return "GCDemo{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
protected void finalize() throws Throwable {
System.out.println("回收了"+name+"年龄 "+age);
}
}