javaDay03-常用类与正则表达式

1.Object

顶级父类中有一些常用方法。

  • hashCode() 根据对象的地址值,计算出一个哈希码值(int)。不同对象的哈希值一般不等,同一个对象的哈希值一定等。
  • getClass() 返回该类的字节码文件对象(Class),这个对象可以再调用如getName(),getSimpleName()方法。这个对象是在类从.java文件编译成.class,.class文件在被加载进内存的时候,jvm给这个字节码文件创建的一个对象,只有一份,不管该类实例化了几个对象,在调用.getclass()方法时返回的字节码文件对象都只有一份。举例:
public class Demo2 {
    public static void main(String[] args) {
        Object obj = new Object();
        System.out.println(obj);
        /*getClass()方法,返回该类的字节码文件对象。
        Object.java-编译->Object.class-->加载进内存
        -->JVM会为object.class创建对象-->通过getClass()方法
        获取字节码文件对象
        注意:Class类型,用来表示字节码文件类型
         */
        Class<?> aClass = obj.getClass();
        Object obj2 = new Object();
        Class<?> aClass1 = obj2.getClass();
        //每new一次为一个新对象,地址值不同
        System.out.println(obj == obj2);//false 
        //注意:字节码文件只有一份
        System.out.println(aClass == aClass1);//true
    }
}
  • toString() 获得对象的地址值,以字符串的形式返回(String)
  • equal() 默认比较两个对象的子地址值,返回布尔值(boolean)(注意:==在比较基本数据类型时,比较值,引用数据类型时,比较地址值)
  • clone()
    在Object中是protect型,在子类可以重写并提升权限。
    类需要实现Cloneable标记接口;
    不调构造方法。
    返回类型为 Object
    浅克隆:克隆出的对象中维护的另一个对象只克隆了地址,没有克隆出维护对象的另一个实例。这时你的原对象和克隆出的对象中维护的是用一个对象,即维护的对象没有被克隆,只有一份。
    深克隆:后面采用io流实现。
    举例:
public class MyTest {
    public static void main(String[] args) throws CloneNotSupportedException {
        Food food = new Food("油泼面");
        Person p = new Person("小明", 25, food);
        p.foodname.foodname="鱼香肉丝";
        Object obj = p.clone();
        //向下转型
        Person p1= (Person) obj;
        p1.name="小花";
        p1.foodname.foodname="回锅肉";

        System.out.println(p.name);//小明
        System.out.println(p.age);//25
        System.out.println(p.foodname.foodname);//回锅肉

        System.out.println("----------------");
        System.out.println(p1.name);//小花
        System.out.println(p1.age);//25
        System.out.println(p1.foodname.foodname);//回锅肉


    }
}


class Person implements  Cloneable{
    String name;
    int age;
    Food foodname;
    public Person() {
    }
    public Person(String name, int age, Food foodname) {
        this.name = name;
        this.age = age;
        this.foodname = foodname;
    }

    @Override
  public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}


class Food{
    String foodname;
    public Food() {
    }
    public Food(String foodname) {
        this.foodname = foodname;
    }
}

2.Scanner

  • new Scanner(IntputStream source) 传入一个输入流,IntputStream对象。
  • 在System这个类中,public static final InputStream in = null;
import java.io.InputStream;
import java.util.Scanner;
public class Demo {
    public static void main(String[] args) {
        //Scanner键盘录入
        /*Scanner(IntputStream source):构造一个Scanner,
           它生成的值从指定的值从指定的输入流进行扫描
         */
        //static IntputStream in标准输入流,此流对应于键盘输入
        InputStream inputStream = System.in;
        Scanner sc = new Scanner(inputStream);
        //System类包含一些有用的类字段和方法,它不能被实例化

        //next ***:从键盘上录入某种数据
        //1.录入数值类型
        sc.nextInt();
        sc.nextLong();
        sc.nextDouble();
        //2.录入字符串类型
        sc.nextLine();
        sc.next();
    }
}
  • hasNext***判断录入类型,返回Boolean,例如:
import java.util.Scanner;
public class Demo1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个整数:");
        if(sc.hasNextInt()){
            int i = sc.nextInt();
            System.out.println(i);
        }else{
            System.out.println("你输入的类型不正确");
        }
    }
}

注意:
使用nextLine时,易出现不录字符串的情况,原因是录入了回车,解决办法,新new一个scanner或者使用next()

3.String类

(1)构造:

  • public String(byte[] bytes)
  • public String(byte[] bytes,int index,int length)
  • public String(char[] value)
  • public String(char[] value,int index,int count)

注意:字符串是常量,它们的值在创建之后不能更改。
例如:
面试:String s = “hello” ;
s = “world” + “java”; 问s的结果是多少?
答:worldjava。
字符串常量创建出来后,存在堆内存的常量池,这个常量池中不能更改,但是引用对象s可以改。在这里插入图片描述
(2)通过new的方式创建对象,实际创建的是两个对象,一个在String pool中,另一个由new开辟内存,将池中对象的地址值付给new的对象。
在这里插入图片描述
(3)字面量赋值时,会先从常量池里面找,有就赋值,没有就创建。

public class Demo3 {
    public static void main(String[] args) {
        //下面的代码中创建了几个对象
        //创建2个对象
        String s1="hello";
        String s2="world";
        String s3="hello";

        System.out.println(s1==s2);    //false
        System.out.println(s1==s3);    //true
    }
}

在这里插入图片描述
面试题:

public class Demo5 {
    public static void main(String[] args) {
        String s1="Hello";
        String s2="Hello";
        String s3="Hel"+"lo";
        String s4="Hel"+new String("lo");
        String s5=new String("Hello");
        String s6=s5.intern();
        String s7="H";
        String s8="ello";
        String s9=s7+s8;

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

解析:

  • s1在创建对象的同时,在字符串池中也创建了其对象的引用。
    由于s2也是利用字面量创建,所以会先去字符串池中寻找是否有相等的字符串,显然s1已经帮他创建好了,它可以直接使用其引用。那么s1和s2所指向的都是同一个地址,所以s1==s2。
  • s3是一个字符串拼接操作,参与拼接的部分都是字面量,编译器会进行优化,在编译时s3就变成“Hello”了,所以s1==s3。
  • s4虽然也是拼接,但“lo”是通过new关键字创建的,在编译期无法知道它的地址,所以不能像s3一样优化。所以必须要等到运行时才能确定,必然新对象的地址和前面的不同。
  • 同理,s9由两个变量拼接,编译期也不知道他们的具体位置,不会做出优化。 s5是new出来的,在堆中的地址肯定和s4不同。
  • s6利用intern()方法得到了s5在字符串池的引用,并不是s5本身的地址。由于它们在字符串池的引用都指向同一个“Hello”对象,自然s1==s6。

(4)String的方法

  • 判断:
  • public boolean equals(Object obj)
  • public boolean equalsIgnoreCase(String str)
  • public boolean contains(String str)
  • public boolean startsWith(String str)
  • public boolean endsWith(String str)
  • public boolean isEmpty()
  • 获取:
  • public int length()
  • public char charAt(int index)
  • public int indexOf(int ch)(这里传char类型的数据会转成int)
  • public int indexOf(String str)
  • public int indexOf(int ch,int fromIndex)(从指定位置(含)后找ch返回索引)
  • public int indexOf(String str,int fromIndex)
  • public String substring(int start)
  • public String substring(int start,int end)(含头不含尾)
  • 转换:
  • public byte[] getBytes()
  • public char[] toCharArray()
  • public static String valueOf(char[] chs)
  • public static String valueOf(int i)
  • public String toLowerCase()
  • public String toUpperCase()
  • public String concat(String str)
  • 替换
  • public String replace(char old,char new)
  • public String replace(String old,String new)
  • 另:
  • public String trim()(去除两端空格)
  • 比较
  • public int compareTo(String str)(取较小字符串的长度,比较这个长度的两者ASCII码差,返回相减后的值,若等,返回长度差)
  • public int compareToIgnoreCase(String str) 忽略大小写比较,举例:
public class Demo7 {
    public static void main(String[] args) {
        //String类的比较字符串功能
        /*public int compareTo(String str) 会对照ASCII 码表
        从第一个字母进行减法运算 返回的就是这个减法的结果
        如果前面几个字母一样会根据两个字符串的长度进行减法运算返回的就是这个减法的结果
      如果连个字符串一模一样 返回的就是0
         */
        int i = "abc".compareTo("abc");
        System.out.println(i);  //0
        int i1 = "abc".compareTo("bbc");
        System.out.println(i1);  //-1
        int i2 = "abc".compareTo("abd");
        System.out.println(i2);  //-1
        int i3="abc".compareTo("abcde");
        System.out.println(i3);   //-2
        /*public int compareToIgnoreCase(String str) 跟上面一样 只是忽略大小写的比较 */
        int i4 = "abc".compareToIgnoreCase("ABC");
        System.out.println(i4);   //0

(5)遍历:

for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            System.out.println(c);
        }

4.StringBuffer

(1)构造:

  • public StringBuffer()
  • public StringBuffer(int capacity)(指定容量,一旦超过会自动扩容量)
  • public StringBuffer(String str)

(2)方法:

  • 获取
  • public int capacity() 获取容量
  • public int length() 获取实际着的字符长度
  • 添加:
  • public StringBuffer append(String str)
  • public StringBuffer insert(int offset,String str)(指定位置处插入字符串)
  • 删除:
  • public StringBuffer deleteCharAt(int index)
  • public StringBuffer delete(int start,int end)
  • 替换:
  • public StringBuffer replace(int start,int end,String str)
  • 反转:
  • public StringBuffer reverse()
  • 查找:
  • int indexOf (String str)
  • nt indexOf (String str,int fromIndex)
  • int lastIndexOf (String str)
  • int lastIndexOf (String str)
  • 截取:
  • public String substring(int start)
  • public String substring(int start,int end)

(3)StringBuffer与String互转

  • String---->StringBuffer(1.构造;2.append();3.insert())
  • StringBuffer---->String()(1.toString();2.substring();3.构造)

(4)StringBuffer(线程安全)与StringBuilder(线程不安全)

(5)传参:

  • String做基本数据类型传,形参不改变实参
  • StringBuffer做引用数据类型,形参会改变实参

(6)StringJoiner(可以指定分隔符和前后缀,只能存字符串)

构造:

  • StringJoiner(CharSequence delimiter) (指定分隔符)
  • StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)(指定分隔符和前后缀)

方法:

  • StringJoiner add(CharSequence newElement)
  • int length()
  • String toString()

注意:String重写了equals方法,但StringBuffer没有重写。

5.Arrays

提供了一些静态方法处理数组。

  • Arrays.toString(arr)
  • Arrays.sort(arr)
  • binarySearch(int[] a, int key)
  • equals(int[] a, int[] a2) (返回boolean)
  • copyOf(int[] original, int newLength) (复制一个数组,从0到newLength长度,不够的补0)
  • copyOfRange(int[] original, int from, int to)(指定位置复制)

6.包装类

byte -------- Byte
short ------- Short
int ----------- Integer
long ---------Long
float -------- Float
double ----- Double
char -------- Character
boolean ---- Boolean

Integer

(1)构造:

  • public Integer(int value)
  • public Integer(String s)(s得是数字,不然报错)

(2)方法:

  • public static int parseInt(String s)
  • intValue()

(3)String与int互转:

int------>String

  • 和""进行拼接
  • String里:public static String valueOf(int i)
  • Integer里:public static String toString(int i)

String------>int

  • Integer里:public static int parseInt(String s)
  • Integer里:intValue()(String – >Integer --> intValue())

(4)自动拆装箱
手动装:valueOf(int)
手动拆:intValue()

(5)Integer 重写了equals方法,比较的是值

面试题:

    Integer i1 = new Integer(127);
	Integer i2 = new Integer(127);
	System.out.println(i1 == i2);//f
	System.out.println(i1.equals(i2));//t
	System.out.println("-----------");

	Integer i3 = new Integer(128);
	Integer i4 = new Integer(128);
	System.out.println(i3 == i4);//f
	System.out.println(i3.equals(i4));//t
	System.out.println("-----------");

	Integer i5 = 128;
	Integer i6 = 128;
	System.out.println(i5 == i6);//f
	System.out.println(i5.equals(i6));t
	System.out.println("-----------");

	Integer i7 = 127;
	Integer i8 = 127;
	System.out.println(i7 == i8);//t
	System.out.println(i7.equals(i8));//t

解析:Integer在自动装箱时,底层是调用valueOf()来进行装箱的,在valueOf()这个方法里,有一个内部类IntegerCache,已经创建好了256个Integer对象到cache[]数组,如果装箱的值在-128-127之间,就会从这里面取一个对象返回,那么就会是同一个对象,如果不在这个范围,则会创建一个新的对象,这样就是不同的对象。

7.正则表达式

使用字符串来定义一个规则,校验数据是否符合该规则。

(1)常用:

        String regx = "abc";
        regx = "[a,b,c]"; //是否匹配我列表中所列举的字符
        regx = "[a-z]"; //列举26个小写字符
        regx = "[A,B,C,D]";
        regx = "[A-Z]";
        regx = "[a-zA-Z]";
        regx = "[^a-zA-Z]"; //不是列表中所列举的
        regx = "[0,1,2]";
        regx = "[0-9]";
        regx = "[a-zA-Z0-9_%]";
        // . 可以匹配单个任意字符
        regx=".";
        regx="..";
        // 我只想要匹配点本身 需要转意
        regx = "\\.";
        // | 表示或者
        regx="|";//匹配空串
        regx = "\\|"; //转意
        regx="a|b";
        regx="\\d"; //跟 [0-9] 意思一样
        regx="\\w"; // \w 单词字符:[a - zA - Z_0 - 9]
        regx = "\\W";  //[^a - zA - Z_0 - 9]
        regx = "\\D"; //跟 [^0-9] 意思一样
        regx="  ";
        regx="\\s"; //匹配空格
        regx="\\S"; //不是空格
        ============================================
        String regx = "[0-9]+";
        regx = "a+b+";
        // * 零次或多次
        regx = "a*";
        //? 一次或一次也没有 比如""空串 就是没有
        regx = "b?";
        regx="\\w+";
        //正好几次
        regx="a{5}";
        regx="[0-9]{5}";
        //  大于等于5 小于等于15
        regx = "[0-9]{5,15}";
        //至少5位
        regx = "[0-9]{5,}";
        regx="^a.+";
        ======================================
        另:
        边界匹配器:
        ^ 行的开头 
		$ 行的结尾 
		\b 单词边界
		就是不是单词字符的地方。例如:要匹配三个字母的单词: 
		String regx = "\\b[a-z]{3}\\b";

案例:

public static void main(String[] args) {
        //定义正则表达式
          /* 需求:校验qq号码.
        1:要求必须是5 - 15 位数字
        2:0 不能开头*/
        String regx = "[1-9][0-9]{4,14}";
        //这个数据是否匹配正则表达式
        boolean b = "asfasdf".matches(regx);

        //校验手机号的规则
        //手机号是 11位 每一位是数字 以1开头 第二位是 3 5 6 7 8 其余位是任意数字
        String phoneRegx="[1][3,5,6,7,8][0-9]{9}";
        boolean f = "13992568959".matches(phoneRegx);
        System.out.println(f);

          //6~18个字符,可使用字母、数字、下划线,需要以字母开头
         //  westos@163.com   abcdhaha@163.com  abc123@163.com ab_c123@163.com
        //网易邮箱的规则

        String mailRegx="[a-zA-Z]\\w{5,17}@163\\.com";
        boolean matches = "Westo_163s@163.com".matches(mailRegx);
        System.out.println(matches);

         String mailRegx2="[a-zA-Z]\\w{5,17}@[a-z]{2,16}\\.(com|cn|net|org)";

         //身份证正则
        String regx3="[1-9]\\d{5}(18|19|20|(3\\d))\\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]";

        //车牌号正则
        String car="[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}";

        //中文正则
        String chinese="[\\u4e00-\\u9fa5]{2,4}";
        boolean matches1 = "王老虎".matches(chinese);
        System.out.println(matches1);

        //可以是字母也可以中文名
        String username = "([a-zA-Z]{6,16})|([\\u4e00-\\u9fa5]{2,4})";
        boolean matches2 = "欧阳非非".matches(username);
        System.out.println(matches2);
    }

(2)使用:
String中的方法:

  • public boolean matches(String regex)
  • public String[] split(String regex) (分割)例如:
	String str="username=张三=23=哈哈";
	String[] strings = str.split("=");
	System.out.println(Arrays.toString(strings));
//自定义规则分割字符串
	String str2 = "1111=asdfasdf2222=asdfasdfas3333=asdfasdfasdf44444";
    String[] split = str2.split("[=a-z]+");
    System.out.println(Arrays.toString(split));
  • public String replaceAll(String regex,String replacement)
    例:
		String str="abc=====122255ccc====33352445477ddd";
        String s = str.replaceAll("[=0-9]+", "=");
        System.out.println(s);

(3)模式器与匹配器:

  • Pattern.compile(“a*b”) (传入正则,返回Pattern类型的对象)
  • matcher(“aaaaab”)(Pattern中的方法,传入字符序列,返回Matcher类型的对象)
  • matches()(Matcher中的方法,返回匹配的结果–boolean)
 public static void main(String[] args) {
        //Pattern  模式器
        //Macher 匹配器
        //模式器:从来封装一个正则表达式
        Pattern p = Pattern.compile("a*b");
        //通过模式器获取匹配器,并且还要传入匹配的数据
        Matcher m = p.matcher("aaaaab");
        //调用匹配器中匹配的方法,进行匹配
        boolean b = m.matches();
        System.out.println(b);
        //如果我们仅仅只是想要知道一个字符串是否符合我们定义的正则,就调用String类中的matches("a*b")方法
        boolean b1 = "aaaaab".matches("a*b");
    }
  • find()和group()(Matcher中的方法)
    注意:先用find()找到,再用group()获取
    例如:
 String str = "da jia ting wo shuo, jin tian yao xia yu, bu shang wan zi xi, gao xing bu?";
        //根据正则来获取
        String regx = "\\b[a-z]{3}\\b";
        //编译正则表达式
        Pattern p = Pattern.compile(regx);
        //获取匹配器,传入你要操作的数据
        Matcher m = p.matcher(str);
      /*  boolean find ()
        尝试查找与该模式匹配的输入序列的下一个子序列。
        String group ()
        返回由以前匹配操作所匹配的输入子序列。
*/
      //第一次查找,先find() 找到再 group()
      /*  boolean b = m.find();
        if (b) {
            String group = m.group();
            System.out.println(group);
        }
        //第二次找
        b = m.find();
        if (b) {
            String group = m.group();
            System.out.println(group);
        }
        b = m.find();
        if (b) {
            String group = m.group();
            System.out.println(group);
        }*/
        while (m.find()){
            String group = m.group();
            System.out.println(group);
        }
    }

8.Math

(1)成员变量:

  • public static final double E
  • public static final double PI

(2)成员方法:

  • public static int abs(int a)
    public static int abs(int a) 取绝对值
    public static double ceil(double a) 向上取整
    public static double floor(double a) 向下取整
    public static int max(int a,int b) 获取最大值
    public static int min(int a, int b) 获取最小值
    public static double pow(double a,double b) 获取a的b次幂
    public static double random() 获取随机数 返回带正号的 double 值,该值 大于等于 0.0 且小于 1.0。
    public static int round(float a) 四舍五入
    public static double sqrt(double a)获取正平方根

9.Random

如果给相同的种子创建Random实例,调用方法生成的数字序列相同。

(1)构造:

  • public Random()
  • public Random(long seed) (给定一个long类型的种子,给定以后每一次生成的随机数是相同的)

(2)成员方法:

  • public int nextInt() (范围为int类型:-2147483648到±2147483648)
  • public int nextInt(int n) (范围0—n-1)
  • void nextBytes(byte[] bytes) (生成随机字节置于空byte数组)

10.System

字段:

  • InputStream in = System.in
  • PrintStream out = System.out (PrintStream中有println()方法)

方法:

  • public static void gc()//调用垃圾回收器
  • public static void exit(int status)//退出java虚拟机 0 为正常退出 非0为 异常退出 (例:System.exit(0))
  • public static long currentTimeMillis()//获取当前时间的毫秒值

11.BigDecimal

(1)构造:

  • public BigDecimal(String val) (将要运算的数据传入,包装为 BigDecimal类)

(2)方法:

  • ublic BigDecimal add(BigDecimal augend)//加
  • public BigDecimal subtract(BigDecimal subtrahend)//减
  • public BigDecimal multiply(BigDecimal multiplicand)//乘
  • public BigDecimal divide(BigDecimal divisor)//除法
  • public BigDecimal divide(BigDecimal divisor,int scale,int roundingMode) (scale 小数点后面保留几位,roundingMode 取舍模式 比如四舍五入)

例如:

		BigDecimal one = new BigDecimal("3.369699999999999999999");
        BigDecimal two= new BigDecimal("10.2525252");
        BigDecimal multiply = one.multiply(two);
        System.out.println(multiply.toString());

12.日期类

Date

(1)构造:

  • public Date()
  • public Date(long date) //把一个long类型的毫秒值转换成一个日期对象(给计算机的元年加上时间量)
		Date date = new Date();
        System.out.println(date);//Tue Feb 02 17:15:13 CST 2021
        Date date1 = new Date(1000 * 60 * 60 * 24);
        System.out.println(date1);//Fri Jan 02 08:00:00 CST 1970

(注:@Deprecated:标注过时)

(2)成员方法:

  • public long getTime(): 获取一个日期对象对象毫秒值(距离计算机元年的毫秒值)
  • public void setTime(long time):

SimpleDateFormat

日期对象与指定格式的字符串互转

(1)构造:

  • public SimpleDateFormat() (默认:2021/2/2 下午6:08)
  • public SimpleDateFormat(String pattern) (指定规则—yyyy:MM:dd HH:mm:ss)

(2)方法:

  • public String format(Date date)
  • public Date parse(String dateStr)(解析的字符串的格式要与传入SimpleDateFormat的构造中的pattern的格式一致)

calendar:(抽象类)(子类GregorianCalendar)

(1)字段(static):

  • YEAR
  • MONTH
  • DAY_OF_MONTH
  • HOUR_OF_DAY
  • MINUTE
  • SECOND

(2)方法:

  • static Calendar getInstance () (calendar不能直接new对象,可以通过这个方法创建)
  • public int get(int field) (传入字段,获取对应值)
  • public void add(int field,int amount)
  • public final void set(int year,int month,int date)

(3)补充:BigInteger概述 可以让超过long范围内的数据进行运算

构造:

  • public BigInteger(String val)

方法:

  • public BigInteger add(BigInteger val)
  • public BigInteger subtract(BigInteger val)
  • public BigInteger multiply(BigInteger val)
  • public BigInteger divide(BigInteger val)
  • public BigInteger[] divideAndRemainder(BigInteger val) (返回结果和余数)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值