9.常用类

常用类

1. 包装类

package com.lin.study.bjsxt.test01;

public class Test {
   public static void main(String[] args) {
       //1.1.利用包装类Integer获取int类型的最值
       System.out.println(Integer.MAX_VALUE);//2147483647
       System.out.println(Integer.MIN_VALUE);//-2147483648
       //1.2."物极必反"
       System.out.println(Integer.MAX_VALUE + 1);//-2147483648
       System.out.println(Integer.MIN_VALUE - 1);//2147483647

       //2.1.手动装箱: int ---> Integer
       Integer i1 = new Integer(12);//构造方法摘要: Integer(int value)
       //2.2.手动拆箱: Integer ---> int
       int n = i1.intValue();
       //3.String ---> int
       Integer i2 = new Integer("12");//构造方法摘要: Integer(String s)

       //4.1.自动装箱: int ---> Integer
       Integer i3 = 12;//底层操作: Integer i3 = Integer.valueOf(12);
       //4.2.自动拆箱: Integer ---> int
       int i4 = i2;

       //5.装箱陷阱
       Integer i5 = 129;
       Integer i6 = 129;
       System.out.println(i5==i6);//false
       //JDK1.5之后,对于自动装箱来说,如果在[-128,127]中的数,
       //则直接返回给你缓存的数(从内部类中的一个缓存数组中获取),
       //如果没在[-128,127]中,就要开辟新空间。


       //6.各种方法
       //6.1.compareTo方法
       System.out.println(i1.compareTo(i2));//0
       /*//底层源码:
       public static int compare(int x,int y){
           return (x<y)?-1:((x==y)?0:1);
       }*/

       //6.2.equals方法
       System.out.println(i1.equals(i2));//true   equals比较的是值是否相等
       System.out.println(i1==i2);//false   "=="比较的是内存地址是否相同

       //6.3.intValue方法
       int i7 = i1.intValue();//Integer ---> int
       System.out.println(i7);//12

       //6.4.parseInt方法
       int i8 = Integer.parseInt("12");//String ---> int
       //6.5.toString方法
       System.out.println(i1.toString() + 12);//1212
       //6.6.valueOf方法
       Integer i9 = Integer.valueOf(12);//int ---> Integer
       Integer i10 = Integer.valueOf("12");//String ---> Integer
  }
}

2. String类

package com.lin.study.bjsxt.test01;

public class Test02 {
   public static void main(String[] args) {
       String str1 = "你好,尚学堂。2018!";
       System.out.println(str1);

       //1.String类中的构造方法
       String str2 = new String();
       String str3 = new String("abc");
       String str4 = new String(new char[]{'a','b','c'});

       //2.String类中的方法
       System.out.println(str1.length());//12
       System.out.println(str2.isEmpty());//true
       System.out.println(str1.isEmpty());//false
       System.out.println(str1.charAt(3));//尚

       String str5 = "abc";
       String str6 = "def";
       System.out.println(str5.equals(str6));//false
       System.out.println(str5==str6);//false

       //compareTo方法
       String str7 = "abc";
       String str8 = "abcdefg";
       System.out.println(str7.compareTo(str8));//-4

       //indexOf: 获取索引
       int num = str8.indexOf('f');
       System.out.println(num);//5

       //subString方法: 字符串截取
       String str9 = str8.substring(2);
       System.out.println(str9);//cdefg
       System.out.println(str8.substring(2,5));//ced   [2,5)左闭右开的区间

       //concat: 拼接字符串
       String str10 = str7.concat(str8);
       System.out.println(str10);//abcabcdefg

       //replace: 替换
       String str11 = str7.replace('a','z');
       System.out.println(str11);//zbc

       //trim: 去掉首位空格
       String str12 = "     a   b   c     ";
       System.out.println(str12.trim());//a   b   c
  }
}
package com.lin.study.bjsxt.test01;

public class Test03 {
   public static void main(String[] args) {

       //1.字符串拼接,会进行编译器优化,直接拼成你想要的字符串。
       String s1 = "abc";
       String s2 = "a" + "b" + "c";
       String s3 = "abc" + "";

       //2.开辟新空间
       String s4 = s1 + "";//变量参与运算,就会在堆中开辟新空间。
       String s5 = new String("abc");

       //测试
       System.out.println(s1==s2);//true
       System.out.println(s1==s3);//true
       System.out.println(s1==s4);//false
       System.out.println(s1==s5);//false
  }
}

3. StringBuilder

package com.lin.study.bjsxt.test01;

public class Test05 {
   public static void main(String[] args) {
       StringBuilder sb = new StringBuilder("0123456789");

       //1.增
       sb.append("这是梦想");
       System.out.println(sb);//0123456789这是梦想

       //2.删
       sb.delete(3,6);//删除位置在[3,6)上的字符
       System.out.println(sb);//0126789这是梦想
       sb.deleteCharAt(6);//删除索引位置在6上的字符
       System.out.println(sb);//012678这是梦想

       //3.改
       //3.1.insert方法
       StringBuilder sb1 = new StringBuilder("$13145920921");
       sb1.insert(5, ",");//在下标为5的位置上插入","
       System.out.println(sb1);//$1314,5920921
       //3.2.replace方法
       StringBuilder sb2 = new StringBuilder("$你好吗5205920921");
       sb2.replace(1,4,"我爱你");//以新字符串替换[1,4)上的字符串
       System.out.println(sb2);//$我爱你5205920921
       //3.3.setCharAt方法
       sb2.setCharAt(4,'!');//在指定索引位置放置一个字符
       System.out.println(sb2);//$我爱你!205920921

       //4.查
       StringBuilder sb3 = new StringBuilder("0123456");
       for (int i = 0; i < sb3.length(); i++) {
           System.out.print(sb3.charAt(i) + "\t");//0 1 2 3 4 5 6
      }
       System.out.println();

       String str = sb3.substring(2,4);
       System.out.println(str);//23
       //截取[2,4)返回的是一个新的String,对StringBuilder没有影响。
  }
}

StringBuilder知识总结:

  1. StringBuilder,StringBuffer的区别

    • StringBuilder JDK1.5 效率高 线程不安全

    • StringBuffer JDK1.0 效率低 线程安全

  2. String类,是不可变类,即一旦一个String对象被创建之后,

    包含在这个对象中的字符序列是不可改变的,直至这个对象被销毁。

  3. StringBuffer类,则是代表一个字符序列可变的字符串,

    可以通过append,insert,reverse,setCharAt,setLength等方法改变其内容。

  4. StringBuilder类,JDK1.5新增了一个StringBuilder类,

    与StringBuffer类基本相似,构造方法和方法基本相同。

 

不同的是StringBuffer是线程安全的,而StringBuilder是线程不安全的,

所以StringBuilder性能略高。

 

通常情况下,创建一个可变的字符串,应该优先考虑使用StringBuilder.

4.模拟集合 ArrayList

MyCollcetion类

package com.lin.study.bjsxt.test02;

public class MyCollection {

   //1.定义属性
   //底层是一个数组 --- Object[]
   Object[] value;
   //数组中被占用的个数
   int size;

   //2.定义构造器
   //2.1.定义空构造器
   public MyCollection() {
       //value = new Object[3];
       this(3);
  }
   //2.2.定义有参构造器
   public MyCollection(int num) {
       value = new Object[num];
  }


   //3.定义放入的方法---add方法
   public void add(Object obj){
       value[size] = obj;
       size++;
       //如果超出范围,就要对数组进行扩容
       if(size>= value.length-1){
           //扩容:创建一个新的数组
           Object[] newObj = new Object[value.length * 2 + 2];
           //将老数组中的东西,复制到新数组中去
           for (int i = 0; i < value.length - 1; i++) {
               newObj[i] = value[i];
          }
           //将value的指向 ---> newObj
           value = newObj;
      }
  }


   //4.定义取出的方法---get方法
   public Object get(int index){
       //如果越界,就要抛出异常!
       if(index<0||index>=size){
           throw new RuntimeException("超出边界!");
      }
       return value[index];
  }

   //重写toString方法
   public String toString() {
       StringBuilder sb = new StringBuilder("[");
       for (int i = 0; i < size; i++) {
           sb.append(value[i] + ",");
      }
       sb.setCharAt(sb.length()-1, ']');
       return sb.toString();
  }
}

Student类

package com.lin.study.bjsxt.test02;

public class Student {
   private String name;
   private int 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;
  }

   public Student(String name, int age) {
       this.name = name;
       this.age = age;
  }

   @Override
   public String toString() {
       return "Student{" +
               "name='" + name + '\'' +
               ", age=" + age +
               '}';
  }
}

测试类: Test

package com.lin.study.bjsxt.test02;

public class Test {
   public static void main(String[] args) {
       //创建集合对象
       MyCollection mc = new MyCollection();

       //1.放入---add方法
       mc.add("abc");
       mc.add(new Student("lili" , 18));
       mc.add(12);//完成自动装箱 Integer i = 12;

       mc.add(36);//开始扩容 ---> this(3)
       mc.add(99);
       mc.add(520);

       //2.取出---get方法
       for (int i = 0; i <= mc.size - 1; i++) {
           System.out.println(mc.get(i));
      }

       //3.越界测试
       //mc.get(-9);

       //4.输出
       System.out.println(mc);//[abc,Student{name='lili', age=18},12,36,99,520]
       System.out.println(mc.toString());//[abc,Student{name='lili', age=18},12,36,99,520]
  }
}

5. 时间处理类

package com.lin.study.bjsxt.test03;

import java.util.Date;

public class Test {
   public static void main(String[] args) {
       //1.java.util.Date:年月日 时分秒
       Date d = new Date();//Thu(周四) Oct(十月) 07(7号) 20:42:56(时间) CST(时区) 2021(年份)
       System.out.println(d);//Thu Oct 07 20:42:56 CST 2021
                             //周四 十月 7号   时间 时区 年份
       //中划线表示过期(废弃)方法---建议你不用的方法
       System.out.println(d.toGMTString());//7 Oct 2021 12:48:13 GMT

       System.out.println(d.toLocaleString());//2021-10-7 20:49:52

       //1.2.常用方法
       System.out.println(d.getYear());//121 + 1900 = 2021
       System.out.println(d.getMonth());//9 返回0~11,其中0表示一月
       System.out.println(d.getDate());//7 月份中的某一天,返回的值在1~31之间
       System.out.println(d.getDay());//4   返回0~6,其中0表示Sunday

       //1.3.获取返回自1970年1月1日00:00:00 GMT以来,此Date对象表示的毫秒数
       System.out.println(d.getTime());//1633613522678
       System.out.println(System.currentTimeMillis());//1633613522721---这个是常用的。原因: 不用创建对象,可以直接调用

       //2.java.sql.Date:年月日
       //2.1.创建一个java.sql.Date的对象
       java.sql.Date sqlDate = new java.sql.Date(1633613522721L);//传入一个long类型的数
       System.out.println(sqlDate);//2021-10-07
       //2.2.String--->java.sql.Date
       java.sql.Date valueOf = java.sql.Date.valueOf("2020-10-01");
       System.out.println(valueOf);//2020-10-01


       //3.java.sql.Date 与 java.util.Date 相互转换:
       //3.1.util ---> sql
       java.sql.Date sqlDate2 = new java.sql.Date(new Date().getTime());
       //3.2.sql ---> util
       Date date = sqlDate2;//向上类型转换
       //结论: sql 是 util 的子类

       //4.java.sql包下的类
       //4.1.java.sql.Time
       java.sql.Time time = new java.sql.Time(1633613522721L);
       System.out.println(time.toGMTString());//7 Oct 2021 13:32:02 GMT---注:这里的时间是指格林威治时间
       //4.2.TimesTamp: 时间戳
       java.sql.Timestamp ts = new java.sql.Timestamp(1633613522721L);
       System.out.println(ts.toGMTString());//7 Oct 2021 13:32:02 GMT

  }
}

6.日期格式化

package com.lin.study.bjsxt.test03;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test2 {
   public static void main(String[] args) {
       //1.String ---> util.Date: 局限: 字符串的格式必须是 年-月-日
       //1.1.第一步:String ---> sql:
       java.sql.Date valueOf = java.sql.Date.valueOf("2020-10-01");
       //1.2.第二步:sql ---> util:
       Date date = valueOf;//向上类型转换

       //2.日期格式化类:
       //这里的格式可以自己设置,之后输出的日期格式,会与这里设置的一样。
       DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss");
       try {
           Date d = df.parse("2020-10-01 12-00-00");//这里输入的格式要与上面自己设置的格式保持一致
           System.out.println(d);//Thu Oct 01 00:00:00 CST 2020
      } catch (ParseException e) {
           e.printStackTrace();
      }

       //3.Date ---> String
       String str = df.format(new Date());//这里输出的格式也会与上面自己设置的格式保持一致!
       System.out.println(str);//2021-10-07 10-45-53

  }
}

7. Calendar类

package com.lin.study.bjsxt.test03;

import java.util.Calendar;
import java.util.GregorianCalendar;

public class CalDemo {
   //Calendar类很强大,但是我们用的少!
   public static void main(String[] args) {
       //1.创建一个日历:
       //Calendar类是抽象类,有以下两种方法创建对象!
       Calendar cal = Calendar.getInstance();
       //Calendar cal = new GregorianCalendar();
       System.out.println(cal);//输出:一堆很长的字

       //2.常用方法
       //2.1.读取
       System.out.println(cal.get(Calendar.YEAR));//2021 --- 2021年
       System.out.println(cal.get(Calendar.MONTH));//9 --- 0~11:这里表示10月
       System.out.println(cal.get(Calendar.DATE));//7 --- 7号
       System.out.println(cal.get(Calendar.DAY_OF_WEEK));//5 --- 这里的1表示周日,所以5表示周四
       /*星期日为一周的第一天 SUN MON TUE WED THU FRI SAT
       DAY_OF_WEEK返回值 1 2 3 4 5 6 7
       星期一为一周的第一天 MON TUE WED THU FRI SAT SUN
       DAY_OF_WEEK返回值 1 2 3 4 5 6 7
       所以Calendar.DAY_OF_WEEK需要根据本地化设置的不同而确定是否需要 “-1”
       Java中设置不同地区的输出可以使用 Locale.setDefault(Locale.地区名) 来实现。*/
       System.out.println(cal.getActualMaximum(Calendar.DATE));//本月最大日: 31
       System.out.println(cal.getActualMaximum(Calendar.MONTH));//月份最大值: 11
       System.out.println(cal.getActualMinimum(Calendar.DATE));//本月最小日: 1

       //2.2.设置
       cal.set(Calendar.DATE, 16);//将当前日期设置为16号
       cal.set(Calendar.MONTH, 7);//将当前月份设置为8月
       cal.set(Calendar.YEAR, 2020);//将当前年份设置为2020年
       System.out.println(cal);//输出:一堆很长的字

       //3.String ---> Calendar
       //3.1.第一步:String ---> Date
       String str = "2020-10-01";
       Date valueOf = java.sql.Date.valueOf(str);
       //3.2.第二步:Date ---> Calendar
       cal.setTime(valueOf);
       System.out.println(cal);//输出:一堆很长的字
  }
}

8. 练习:日历

package com.lin.study.bjsxt.test03;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Scanner;

public class Test03 {
   public static void main(String[] args) {
       //1.用户录入
       System.out.println("请输入你想要查看的日期: (格式例如:2020-10-01): ");
       Scanner sc = new Scanner(System.in);
       String str = sc.next();

       //2.将字符串转换为Calendar类: String ---> Calendar
       //2.1.第一步: String ---> sql.Date
       Date valueOf = java.sql.Date.valueOf(str);
       //2.2.第二步: sql.Date ---> Calendar
       Calendar cal = new GregorianCalendar();
       cal.setTime(valueOf);
       //System.out.println(cal);//测试语句

       //3.制作表头
       System.out.println("日\t一\t二\t三\t四\t五\t六\t");
       int count = 0;//引入一个计数变量: 用于换行

       //4.求出用户输入的月中的最大天数:
       int maxDay = cal.getActualMaximum(Calendar.DATE);
       //System.out.println(maxDay);//31---此处用于测试

       //5.制作每个月份前的空格
       //5.1.获取用户输入的是哪一天:
       int nowDay = cal.get(Calendar.DATE);
       //5.2.将用户输入的日期变成本月的第一天
       cal.set(Calendar.DATE, 1);
       //5.3.获取这个第一天是本周的第几天
       int num = cal.get(Calendar.DAY_OF_WEEK);
       //System.out.println(num);

       //5.4.设置空格
       for (int i = 1; i <= num - 1; i++) {//"\t"的个数: num-1
           System.out.print("\t");
      }
       count = num - 1;


       //6.打印出日历
       for (int i = 1; i <= maxDay; i++) {
           if(i!=nowDay){
               System.out.print(i + "\t");
          }else{
               System.out.print(i + "*\t");
          }
           count++;
           if(count%7==0){
               System.out.println();
          }
      }
  }
}

运行结果:

请输入你想要查看的日期: (格式例如:2020-10-01): 2021-10-01 1* 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Process finished with exit code 0

9. 枚举类

1.未引入枚举类时

Person类

package com.lin.study.bjsxt.test05;

public class Person {
   private String name;
   private int age;
   private String sex;

   //1.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;
  }

   public String getSex() {
       return sex;
  }

   //修改此方法
   public void setSex(String sex) {
       if("男".equals(sex)||"女".equals(sex)){
           this.sex = sex;
      }else{
           //方式一:设置默认值
           //this.sex = "男";
           //方式二:抛出自定义异常---RuntimeException:运行时异常
           throw new RuntimeException("性别只能是男/女");
      }
  }

   //2.构造器
   public Person(String name, int age, String sex) {
       this.name = name;
       this.age = age;
       this.sex = sex;
  }
   public Person() {
  }

   //3.toString方法

   @Override
   public String toString() {
       return "Person{" +
               "name='" + name + '\'' +
               ", age=" + age +
               ", sex='" + sex + '\'' +
               '}';
  }
}

Test类

package com.lin.study.bjsxt.test05;

public class Test {
   public static void main(String[] args) {
       Person p = new Person();
       p.setName("lili");
       p.setAge(19);
       p.setSex("男");
       System.out.println(p);//Person{name='lili', age=19, sex='男'}
  }
}

2.引入枚举类

Gender枚举类

package com.lin.study.bjsxt.test06;

public enum Gender {
   男,女;
}

Person类

package com.lin.study.bjsxt.test06;

public class Person {
   private String name;
   private int age;
   private Gender sex;

   //1.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;
  }

   public Gender getSex() {
       return sex;
  }

   public void setSex(Gender sex) {
       this.sex = sex;
  }
   //2.构造器
   public Person(String name, int age, Gender sex) {
       this.name = name;
       this.age = age;
       this.sex = sex;
  }
   public Person() {
  }
   //3.toString方法
   @Override
   public String toString() {
       return "Person{" +
               "name='" + name + '\'' +
               ", age=" + age +
               ", sex=" + sex +
               '}';
  }
}

Test类

package com.lin.study.bjsxt.test06;

public class Test {
   public static void main(String[] args) {
       Person p = new Person();
       p.setName("lili");
       p.setAge(19);
       p.setSex(Gender.男);
       System.out.println(p);//Person{name='lili', age=19, sex=男}

       Gender sex = Gender.女;
       switch(sex){
           case 男:
               System.out.println("这是男孩!");break;
           case 女:
               System.out.println("这是女孩!");break;
      }
  }
}

枚举总结:

  1. 枚举与switch结合应用

    • switch的()里只能放: int,short,byte,char,String,枚举

    • case后面只能是枚举下的实例

  1. 什么情况下使用枚举: 值固定的时候!

10.Math类

package com.lin.study.bjsxt.test07;

public class Test {
   public static void main(String[] args) {
       //1.圆周率
       System.out.println(Math.PI);//3.141592653589793

       //2.次幂
       System.out.println(Math.pow(3.0, 3.0));//27.0
       //3.开平方
       System.out.println(Math.sqrt(9.0));//3.0

       //4.向上取整数
       System.out.println(Math.ceil(9.1));//10.0
       //5.向下取整数
       System.out.println(Math.floor(9.1));//9.0
       //6.四舍五入取整数
       System.out.println(Math.round(5.8));//6---这里会返回一个int/long的数

       //7.随机数
       System.out.println(Math.random());//返回一个[0.0,1.0)中的随机数

       //8.绝对值
       System.out.println(Math.abs(-9.8));//9.8

       //9.取最大/小值
       System.out.println(Math.max(3.3, 6.6));//6.6
       System.out.println(Math.min(3.3, 6.6));//3.3
  }
   //若有一个自定义的Math类中重名的方法,如:sqrt
   public static double sqrt(double d){
       return 8.8;
  }
   //则程序会执行就近原则,即程序会执行这个方法,而不去执行Math类中的sqrt方法
}

知识小店:

若将包import static void java.lang.Math.*导入

则在调用方时,可以省略 "Math."

即:Math.PI 可直接写成 PI

11. Random类

package com.lin.study.bjsxt.test07;

import java.util.Random;

public class Test02 {
   public static void main(String[] args) {
       //Random类===》随机数===》导包:java.util.Random
       //Random r = new Random(10);
       /*若入参是一个固定的long类型的值,那么程序会返回确定的一系列随机数。*/
       Random r = new Random(System.currentTimeMillis());
       /*故以系统时间作为随机数生成器的种子,因为时间是一直变化的long类型数*/
       for (int i = 1; i <= 3; i++) {
           System.out.println(r.nextInt());
      }

       Random r2 = new Random();//空构造器---以纳秒作为种子
       for (int i = 1; i <= 3; i++) {
           System.out.println(r2.nextBoolean());
           System.out.println(r2.nextDouble());//产生[0.0,1.0)中的随机浮点数
           System.out.println(r2.nextInt(10));//产生[0,10)中的随机整形数
      }
  }
}

 

posted @ 2021-10-08 23:34  木木9_9  阅读(15)  评论(0)    收藏  举报