JAVA自学笔记(Object常用类)

1、Object类

  • 超类、基类,所有类的直接或者间接父类,位于继承树的最顶层

  • 任何类,如果没有书写extends显示继承某个类,全都默认直接继承Object类,否则为间接继承

  • Object类中所定义的方法,是所有对象都具备的方法

  • Object类型可以存储任何对象。

    • 作为参数,可接受任何对象

    • 作为返回值,可以返回任何对象。

1.1、getClass()方法

  • public final Class<?> getClass(){}

  • 返回引用中存储的实际对象类型

  • 应用:通常用于判断两个引用中实际存储对象类型是否一致。

  • public class TestgetClass {
        public static void main(String[] args) {
            Student student1 = new Student("张三",15);
            Student student2 = new Student("李四",18);
            Square square = new Square(12);
            Class class1 = student1.getClass();
            System.out.println(class1);
            Class class2 = student2.getClass();
            Class class3 = square.getClass();
            if(class1 == class2){
                System.out.println("s1和s2是同一个类型");
            }else {
                System.out.println("s1和s2不是同一个类型");
            }
            if(class1 == class3){
                System.out.println("s1和Square是同一个类型");
            }else {
                System.out.println("s1和Square不是同一个类型");
            }
        }
    }
    //输出结果
     class com.qf.day12_2.Student(Student student1 = new Student("张三",15);      Class class1 = student1.getClass();)
     s1和s2是同一个类型  //(class1 == class2)
     s1和Square不是同一个类型  //(class1 == class3)

1.2hashCode()方法

  • public int hashCode(){}。

  • 返回该对象的哈希码值。

  • 哈希值根据对象的地址字符串数字使用hash算法计算出来的int类型的数值。

  • 一般情况下相同对象返回相同的哈希码。

  • 同类型对象返回的哈希值不一样。

  • public class TestgetClass {
        public static void main(String[] args) {
            Student student1 = new Student("张三",15);
            Student student2 = new Student("李四",18);
            int hashCode1 = student1.hashCode();
            int hashCode2 = student1.hashCode();
            int hashCode3 = student2.hashCode();
            if(hashCode1 == hashCode2){
                System.out.println("s1两次返回的哈希值一样");
            }else {
                System.out.println("s1两次返回哈希值不一样");
            }
            if(hashCode1 == hashCode3){
                System.out.println("s1和s2的哈希值一样");
            }else {
                System.out.println("s1和s2的哈希值不一样");
            }
        }
    }
    //输出结果
    s1两次返回的哈希值一样
    s1和s2的哈希值不一样

1.3、toString()方法

  • public String toString (){}

  • 返回该对象的字符串表示(表现形式)

  • 可以根据程序需求覆盖该方法。如:展示对象各个属性。

Student student2 = new Student("李四",18);
System.out.println(student2.toString());
//输出结果
com.qf.day12_2.Student@73035e27(哈希值)

1.4、equals()方法

  • ==(基础数据类型比较数值,引用类型比较地址)

  • public Boolean equals(Object obj){}

  • 默认实现为(this = = obj),比较两个对象地址是否相等。

  • 可以进行覆盖,比较两个对象的内容是否相等。(覆盖步骤)

    • 比较两个引用是否指向同一个对象

    • 判断obj是否为null

    • 判断两个引用指向的实际对象类型是否一致

    • 强制类型转换

    • 依次比较各个属性值是否相等

@Override
public boolean equals(Object obj) {
    //判断两个引用是否指向同一个对象
    if(this == obj){
        return true;
    }
    //判断obj是否为null
    if(obj == null){
        return false;
    }
    //判断两个运用指向的实际对象是否一致
    if(obj instanceof Student) {
        //强制类型转换
        Student s = (Student)obj;
        //依次比较各个属性值是否相等
        if(this.name.equals(s.getName()) && this.age == s.getAge()){
            return true;
        }
    }
    return false;
}

1.5、finalize()方法

  • 当对象被判定为垃圾对象时,由JVM自动调用此方法,用以标记垃圾对象,进入回收队列

  • 垃圾对象:没有有效引用指向此对象时,为垃圾对象

  • 垃圾回收:由GC销毁垃圾对象,释放数据存储空间

  • 自动回收机制:JVM的内存耗尽,一次性回收所有垃圾对象。

  • 手动回收机制:使用System.gc();通知JVM执行垃圾回收。

2、包装类

2.1、什么是包装类

  • 基本数据类型所对应的引用数据类型。(基础数据类型直接存储在栈内存中,引用类型存放在堆内存中)

  • Object可统一所有数据,包装类的默认值是null;

  • 包装类对应关系

基本数据类型包装类型
intInteger
shortShort
longLong
doubleDouble
charCharacter
booleanBoolean
floatFloat
byteByte

2.2、类型转换和装箱与拆箱

  • 装箱:基本数据类型装换为引用数据类型

  • int i = 100;
    Integer integer = new Integer(100);
  • 拆箱:引用数据类型转换为基本数据类型

  • int n2 = integer.intValue();
  • JDK1.5之后提供自动装箱和拆箱

  • num = integer3.valueOf()  //自动拆箱
  • parseXXX()静态方法,(装换为XXX类型)

  • valueOf()静态方法。

  • 注意:需要保证类型兼容,否则抛出NumberFormatException异常。

2.3、Integer缓冲区

  • JAVA预先创建了256个常用的整数包装类型对象。【-128~127】,256个常用整数已经提前创建好,内存地址已经分配好了。在实际开发中,对已经创建的对象进行复用。节省内存消耗

public static void main(String[] args) {
    Integer integer1 = new Integer(100);
    Integer integer2 = new Integer(100);
    System.out.println(integer1 == integer2);//false
​
    Integer integer3 = Integer.valueOf(127);
    Integer integer4 = Integer.valueOf(127);
    System.out.println(integer3 == integer4);//true
​
    Integer integer5 = Integer.valueOf(-128);
    Integer integer6 = Integer.valueOf(-128);
    System.out.println(integer5 == integer6);//true
​
    Integer integer7 = Integer.valueOf(128);
    Integer integer8 = Integer.valueOf(128);
    System.out.println(integer7 == integer8);//false,内存地址不一样
}

3、String类

  • 字符串是常量,创建之后不可改变

  • 基础类型转换换成字符串

    • //字符串转换为String类型
      int num = 10;
      //1.:使用 +
      String  s = num + "";  //输出:10
      
      //2.使用Integer提供的方法
      String s2 = Integer.toString(num); //输出:10
      
      //二进制字符串类型
      String s3 = Integer.toBinaryString(num);//输出:1010
      
      //十六进制字符串类型
      String s4 = Integer.toHexString(num); //输出:A
      
      //字符串转换为基础类型
       String s5 = "1000";
       int n = Integer.parseInt(s5);  //输出: 1000
      
       //特殊Boolean类型转换
       String  s6 = "true"; // 字符串除了true之外,转化为Boolean全是false
       boolean b = Boolean.parseBoolean(s6);  //输出:true
  • 字符串字面值存储在字符串池,可以共享。JDk1.7之前存储在方法区中,JDK1.7之后移动到堆中

  • String name = "hello";//"hello"常量存储在字符串池中

  • String name = "hello";//"hello"常量存储在字符串池中
    name = "zhangsan";//“zhangsan”赋值给name变量,给字符串赋值时,并没有修改数据,而是重                     //新开辟空间赋给name

  • String name = "hello";//"hello"常量存储在字符串池中
    name = "zhangsan";//“zhangsan”赋值给name变量
    String name2 = "zhangsan";//首先去字符串池中寻找“zhangsan”,如果有,则                                      //将“zhangsan”的地址给name2,如果没有,创建空间存储

  • String s = "Hello ";产生一个对象,字符串池中存储

  • String str = new String("java "); 创建两个对象,堆、池各存储一个。

  • ==比较地址 String中的equal被重写,比较char数组,内容一样就返回true

  • String address = "北京";
    String address1 = new String("北京");
    System.out.println(address==address1);  //输出结果:false
    System.out.println(address.equals(address1);//输出结果:true
    
    String address2 = new String("北京");
    System.out.println(address2==address1);//输出结果:false
    System.out.println(address2.equals(address1);//输出结果:true
  • String str = new String("java ");

String str2 = new String("java ");

System.out.println(str == str2); //false

3.1、常用方法

  • public int length ()返回字符串长度(空格也算字符)

  • String  test = "adSHOqwno45668asdas";
    int i = test.length();
    System.out.println("字符串的长度:"+i);
    //输出结果:字符串的长度:19
  • public char charAt(int index)根据下标获取字符

  • char c = test.charAt(5);
    System.out.println("test的第5个下标的字符是:"+c);
    //输出结果:test的第5个下标的字符是:q
  • public boolean contains(String str)判断当前字符串中是否包含str

boolean b = test.contains("wno456");
System.out.println("test中包含wno456:"+ b);
//输出结果:test中包含wno456:true
  • public char[] toCharArray() 将字符串转换成数组

  • System.out.println(Arrays.toString(test.toCharArray()));
    //输出结果:[a, d, s, h, o, q, w, n, o, 4, 5, 6, 6, 8, a, s, d, a, s]
  • public int indexOf(String str) 查找str首次出现的下标,存在则返回该下标,不存在返回-1

  • System.out.println(test.indexOf("wno456"));
    //输出结果:6
  • public int lastIndexOf(String str)查找字符串在当前字符串中最后一次出现的下标索引。

  • System.out.println(test.lastIndexOf("as"));
    //输出结果:17
  • public String trim() 去掉字符串前后的空格

  • System.out.println(test.trim());
    //输出结果:adSHOqwno45668asdas
  • public String toUpperCase() 将小写转成大写

  • System.out.println(test.toUpperCase());
    //输出结果:ADSHOQWNO45668ASDAS
  • public boolean endWith(String str) 判断字符串是否以str结尾

  • System.out.println(test.endsWith("as"));
    //输出结果:true
  • public String replace(char oldChar , char newChar)将旧字符串替换成新字符串

  • System.out.println(test.replace("6","@"));
    //输出结果:adSHOqwno45@@8asdas
  • public String[] split(String str) 根据str将字符串拆分,[ a,]可以选择多个分隔符,使用两个分割标记,[ a,]+“+”表示可以出现多个a或者,进行分割 + 正则表达式表示前面的空格可以出现一次或者多次

  • System.out.println(Arrays.toString(test.split(&quot;a&quot;)));
    //输出结果:[, dSHOqwno45668, sd, s]
  • equalsIgnoreCase:忽略大小写比较

  • String s1 = "hello";
    String s2 = "HELLO";
    System.out.println(s1.equalsIgnoreCase(s2));
    //输出结果:true
  • compareTo() 通过字典比较大小

String s3 = "abc"; //a在字典97
String s4 = "xyz";  //z在字典122
System.out.println(s3.compareTo(s4));
//输出结果:-23
  • compareTo() 通过字典比较大小,第一个比完比第二个。如果s4的长度大于s3,并且s3的全部和s4的前面一样,此时返回长度的差异,两个一模一样返回:0

  • String s3 = "abc"; 
    String s4 = "abczty";  
    System.out.println(s3.compareTo(s4));
    //输出结果:-3
public static void main(String[] args) {
    String  string = "java是世界最好的语言,我爱java,java真香";
    //返回指定下标的字符
    char c = string.charAt(string.length()-1);
    System.out.println(c);  //输出结果:香
    //判断传递的参数是否在字符串中
    boolean b = string.contains("最好");
    boolean b1 = string.contains("PHP");
    System.out.println(b);  //输出结果:true
    System.out.println(b1);  //输出结果:false
    //将字符串转成字符串数组
    char[] chars = string.toCharArray();
    System.out.println(chars);   //输出结果:java是世界最好的语言,我爱java,java真香
    System.out.println(chars.length);  //输出结果:26
    
    //返回参数字符串在字符串的首次出现的位置    从下标6开始
    int pos=string.indexOf("java",6);
    System.out.println(pos);   //输出结果:15
    //需求:打印Java出现的所以位置
    //返回字符串的长度
    System.out.println(string.length());26
    //trim(),去掉字符串的前后空格。
    String str2 = "   hello   word    ";
    System.out.println(str2);   //输出结果:      hello   word  
    System.out.println(str2.trim());   //输出结果:hello   word

    //将字符串转换为大写(toUpperCase) ,小写(toLowerCase)
    System.out.println(str2.trim().toUpperCase());   //输出结果:HELLO   WORD

    //判断字符串是否以参数结尾
    String filename = "HelloWord.java";
    System.out.println(filename.endsWith(".java"));  //输出结果:true
    //判断字符串是否以参数开始
    System.out.println(filename.startsWith("Hello"));   //输出结果:true

    //replace  替换,将旧字符串转换为新字符串
    String  str3 = string.replace("java","PHP");
    System.out.println(str3);   //输出结果:PHP是世界最好的语言,我爱PHP,PHP真香

    //split:拆分
    String city  = "北京,上海,南京,郑州";
    String[] cities = city.split(",");
    for(String c1 : cities){
        System.out.print(c1+"\t");   //输出结果:北京,上海,南京,郑州    
    }

    //subString  截取(含头不含尾)
    String str4 = string.substring(string.indexOf("我"));
    System.out.println(str4);   //输出结果:我爱java,java真香
}

4、StringBuilder和StringBuffer(可变长字符串)

  • 概念:可在内存中创建可变的缓存空间,存储频繁改变的字符串。效率远高于String

  • StringBulider:可变长字符串,JDK5.0提供,运行效率快、线程不安全

  • StringBuffer:可变字长符串,JDK1.0提供,运行效率慢、线程安全

  • StringBulider和StringBuffer常用方法

public static void main(String[] args) {
    StringBuilder sb = new StringBuilder();
    //追加(append)
    sb.append("java是最好的语言");
    sb.append(",我爱PHP");
    sb.append(",我讨厌C语言");
    System.out.println(sb);   //java是最好的语言,我爱PHP,我讨厌C语言
    //添加(insert)
    sb.insert(0,"hello,");
    System.out.println(sb);  //hello,java是最好的语言,我爱PHP,我讨厌C语言
    //替换(replace) 含头不含尾
    sb.replace(0,1,"H"); 
    System.out.println(sb);//Hello,java是最好的语言,我爱PHP,我讨厌C语言
    //删除(delete)含头不含尾 从0开始
    sb.delete(0,6);
    System.out.println(sb);  //java是最好的语言,我爱PHP,我讨厌C语言
    //清空
    sb.delete(0,sb.length());
    System.out.println(sb.length());  //0
    //reverse   反转
    StringBuilder sb = new StringBuilder("java是世界最好的语言,我爱java,java真香");
    System.out.println(sb);   //java是世界最好的语言,我爱java,java真香
    System.out.println(sb.reverse());  //香真avaj,avaj爱我,言语的好最界世是avaj
}
  • StringBuilder运行效率

  • 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));   //用时:10
String sb = "";
long start = System.currentTimeMillis();
for(int i=0 ;i<99999;i++){
    sb = sb +i;
}
long end = System.currentTimeMillis();
System.out.println("用时:"+ (end-start)); //用时:4138

5、BigDecimal类

  • 很多实际应用中需要精确运算,但是double是近似值存储,不符合要求,所以使用BigDecimal提高精度。

  • double d1 = 1.0;
    double d2 = 0.9;
    System.out.println(d1-d2);  //0.09999999999999998
    
    double result = (1.4-0.5)/0.9;
    System.out.println(result);  //0.9999999999999999
  • 位置:java.math包中

  • 作用:精确计算浮点数

  • 创建方式:

    BigDecimal   bd   =   new   BigDecimal  (" 1.0 ")  ;
  • 常用方法

  • //add  加法
    System.out.println((new BigDecimal("1.0")).add(new BigDecimal("0.9")));  //1.9
    //subtract  减法
    System.out.println((new BigDecimal("1.0")).subtract(new BigDecimal("0.9")));  //0.1
    //multiply  乘法
    System.out.println((new BigDecimal("1.0")).multiply(new BigDecimal("0.9")));  //0.90
    //divide  除法  BigDecimal.ROUND_HALF_UP  四舍五入     2  保留两位小数
    System.out.println((new BigDecimal("20")).divide(new BigDecimal("3"),2,BigDecimal.ROUND_HALF_UP));  //6.67
    
      //除法的问题,除不尽的时候需要保留小数的位数(scale),四舍五入(roundingMode.HALF_UP)五舍六入(roundingMode.HALF_DOWN)
            BigDecimal bd3 = new BigDecimal("10");
            BigDecimal bd4 = new BigDecimal("3");
            BigDecimal result5 = bd3.divide(bd4,21, RoundingMode.HALF_UP);
            System.out.println(result5);

6、Math类

System.out.println(Math.E);   //  2.718281828459045
//圆周率
System.out.println(Math.PI);  //3.141592653589793
//立方根
System.out.println(Math.cbrt(27));  //3.0
//平方根
System.out.println(Math.sqrt(9));  //3.0
//返回大于或者等于这个数的最小整数
System.out.println(Math.ceil(3.8));  //4.0
//返回小于或者等于这个数的最大整数
System.out.println(Math.floor(5.5));   //5.0
//pow  返回a数的b次幂
System.out.println(Math.pow(2,10));   //1024.0
//random  返回0-1之间的小数   不等于1,可以等于0
System.out.println(Math.random());    //0.9454350386657077
//需求:返回一个0-9之间的一个小数
System.out.println((int)(Math.random()*10));  //4
//需求  返回50-100之间的随机数  (a到b之间的数   Math.random()*(b-a+1)+a)
System.out.println((int)(Math.random()*51)+50);  //85
//需求  返回100-999之间的随机数  (999-100+1)
System.out.println((int)(Math.random()*(999-100+1))+100);   //466
//round() 返回整数  四舍五入取整
System.out.println(Math.round(3.1415926));  //3
System.out.println(Math.round(3.6663));   //4
//round()保留两位小数
System.out.println(Math.round(3.1415926*100)/100.0);   //3.14

//总结四舍五入的方法
// (1)System.out.printf   %.2f
//  (2)Math.round();
// (3)DecimalFormat类实现
DecimalFormat df = new DecimalFormat("#.00"); //#表示整数位置  ,00表示两位小数
System.out.println(df.format(3.1415926));   //3.14
//  (4)BigDecimal类实现
BigDecimal bd = new BigDecimal("3.1415926");
System.out.println(bd.setScale(2, RoundingMode.HALF_UP));   //3.14

7、Date类、Calenda类

  • Date表示特定的瞬间,精确到毫秒。Date类中的大部分方法已经被Calender类中的方法取代。

  • 事件单位

    • 1秒=1000毫秒

    • 1毫秒= 1000微秒

    • 1微秒 =1000纳秒

    //今天
    Date date = new Date();
    System.out.println(date.getTime());
    System.out.println(date.toString());
    //昨天
    Date yes = new Date(date.getTime()-60*60*24*1000);
    System.out.println(yes.toString());
    System.out.println("________________________________________________________");
    //创建日历对象
            Calendar calendar = Calendar.getInstance();
    //获取年
    System.out.println(calendar.get(Calendar.YEAR));   //2021
    //获取月
    System.out.println(calendar.get(Calendar.MONTH)+1);  //6
    //获取日
    System.out.println(calendar.get(Calendar.DAY_OF_MONTH));   //5
    //获取小时
    System.out.println(calendar.get(Calendar.HOUR_OF_DAY));  //15
    //获取分钟
    System.out.println(calendar.get(Calendar.MINUTE));    //31
    //获取秒
    System.out.println(calendar.get(Calendar.SECOND));   //10
    
    //设置时间
    //创建  2010-10-1 15:30:20
    Calendar calendar1 = Calendar.getInstance();
    calendar1.set(2010,9,1,15,30,20);
    System.out.println(calendar1.getTime().toString());   //Fri Oct 01 15:30:20 CST 2010
    
    //add 添加或者减少指定的时间
    Calendar yes1 = Calendar.getInstance();
    yes1.add(Calendar.DAY_OF_MONTH,-1);
    System.out.println(yes1.getTime().toString());   //Fri Jun 04 15:31:10 CST 2021
    
    Calendar tomorrow  = Calendar.getInstance();
    tomorrow.add(Calendar.DAY_OF_MONTH,1);
    System.out.println(tomorrow.getTime().toString());  //Sun Jun 06 15:31:10 CST 2021
      //当前月的最小条数,最大天数
     System.out.println(calendar.getActualMaximum(Calendar.DAY_OF_MONTH));  //30
     System.out.println(calendar.getActualMinimum(Calendar.DAY_OF_MONTH));   //1

8、System类

//Systrm :系统类的使用
//arraycopy():复制数组
//src  复制的原数组  srcPos: 从哪个位置开始复制  dest:目标数组
//destPos:从目标数组的那个位置开始存放   length:复制的长度
int[] arr = {10,8,20,4866,6541,51};
int[] dest = new int[arr.length*2];
System.arraycopy(arr,0,dest,4,5);
System.out.println(Arrays.toString(dest));   //[0, 0, 0, 0, 10, 8, 20, 4866, 6541, 0, 0, 0]

//currentTimeMillis();返回从1790.1.1(UNIX出现)到现在的好描述,用来计算代码的执行时间
System.out.println(System.currentTimeMillis());   //1622880403100

//System.gc();  告诉垃圾回收器回收垃圾

//System.exit(status);0  表示正常退出  非0  非正常退出
System.exit(0);
System.out.println("程序结束.....");  //无输出

9、SimpleDateFormat类

Date date = new Date();
System.out.println(date.toString());  //Sat Jun 05 16:11:24 CST 2021
//格式化时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println(sdf.format(date));  //2021-06-05 04:12:05

//解析时间(字符串转化为时间)
String s = "2020-05-06 17:20:30";
Date date1 = sdf.parse(s);
System.out.println(date1);  //Wed May 06 17:20:30 CST 2020

10、Runtime类

// 获取运行时对象
Runtime runtime = Runtime.getRuntime();
System.out.println(runtime);
//exec();在单独的进程中执行命令
Process p = runtime.exec("notepad");  //打开记事本

Thread.sleep(5000);

//销毁进程
p.destroy();  //关闭记事本
//exit() 退出JVM   System中的exit调用的就是runtime的exit
//gc()    告诉垃圾回收器回收垃圾   System中的gc调用的就是runtime的gc
//打印程序所占(堆)的内存空间
System.out.println("总的内存大小:"+ runtime.totalMemory()/1024/1024 + "MB");  //总的内存大小:128MB
 System.out.println("空闲内存大小:"+ runtime.freeMemory()/1024/1024 + "MB");   //空闲内存大小:124MB
 System.out.println("最大内存大小:"+ runtime.maxMemory()/1024/1024 + "MB");    //最大内存大小:2018MB

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值