Day15

Day15

一,字符串类

1,String的使用

public class Test01 {
	/**
	 * 知识点:关于字符串的类
	 * 		分类:String、StringBuffer、StringBuilder
	 * 
	 * 知识点:String的使用
	 */
	public static void main(String[] args) {
		
		String str = "123abc";
		
		str = str.concat("DEF123");//拼接字符串,并返回新的字符串
		str = str.substring(3);//从开始下标处截取到字符串末尾,并返回新的字符串
		str = str.substring(1, 6);//从开始下标处(包含)截取到结束下标处(排他),并返回新的字符串
		
		str = str.toUpperCase();//转大写,并返回新的字符串
		str = str.toLowerCase();//转小写,并返回新的字符串
		
		str = "   123  abcDE  F12  3     ";
		
		str = str.trim();//去除首尾空格,并返回新的字符串
		str = str.replace('2', 'x');//替换字符,并返回新的字符串
		str = str.replaceAll("1x", "aaa");//替换字符串,并返回新的字符串
		str = str.replaceAll(" ", "");//替换字符串,并返回新的字符串(去除字符串中所有的空格)
		
		str = "123abcDEF1234";
		System.out.println(str);//123abcDEF1234
		
		System.out.println("判断字符串是否以某个字符串开头:" + str.startsWith("123"));//true
		System.out.println("判断字符串是否以某个字符串结尾:" + str.endsWith("1234"));//true
		
		System.out.println("获取子字符串在此字符串中第一次出现的下标:" + str.indexOf("12"));//0
		System.out.println("获取子字符串在此字符串中最后一次出现的下标:" + str.lastIndexOf("12"));//9
		
		System.out.println("获取指定下标上的字符:" + str.charAt(6));//D
		
		System.out.println("----------------------------");
		
		//将其他类型转换为字符串
		System.out.println(String.valueOf(100));//"100"
		System.out.println(String.valueOf(123.123));//"123.123"
		System.out.println(String.valueOf(true));//"true"
		System.out.println(String.valueOf('a'));//"a"
		
		
		//将其他类型转换为字符串 - 简便写法
		System.out.println(100 + "");//"100"
		System.out.println(123.123 + "");//"123.123"
		System.out.println(true + "");//"true"
		System.out.println('a' + "");//"a"
	
	}
}

2,StringBuffer的使用

public class Test02 {
	/**
	 * 知识点:StringBuffer的使用
	 */
	public static void main(String[] args) {
		
		StringBuffer sb = new StringBuffer();
		
		sb.append("123abc");//在末尾追加内容
		sb.append("DEF123");//在末尾追加内容
		
		sb.insert(6, "xyz");//在指定下标处插入数据
		
		sb.deleteCharAt(5);//删除指定下标上的字符
		sb.delete(3, 11);//从开始下标处(包含)删除到结束下标处(排他)的字符
		
		sb.reverse();//反转字符串
		
		sb.replace(1, 4, "用良心做教育");//从开始下标处(包含)替换到结束下标处(排他)的字符
		
		System.out.println(sb);//321321

	}
}

3,StringBuilder的使用

public class Test03 {
	/**
	 * 知识点:StringBuilder的使用
	 */
	public static void main(String[] args) {
		
		StringBuilder sb = new StringBuilder();
		
		sb.append("123abc");//在末尾追加内容
		sb.append("DEF123");//在末尾追加内容
		
		sb.insert(6, "xyz");//在指定下标处插入数据
		
		sb.deleteCharAt(5);//删除指定下标上的字符
		sb.delete(3, 11);//从开始下标处(包含)删除到结束下标处(排他)的字符
		
		sb.reverse();//反转字符串
		
		sb.replace(1, 4, "用良心做教育");//从开始下标处(包含)替换到结束下标处(排他)的字符
		
		System.out.println(sb);//321321

	}
}

4,String的深入

public class Test04 {
	/**
	 * 知识点:深入String - 面试题
	 */
	public static void main(String[] args) {
		
		//面试题1:描述下列代码会创建几个String对象
		//答案:1个,"abc"为字面值常量,存储在常量池中,常量池中的数据不允许重复
//		String str1 = "abc";
//		String str2 = "abc";
		
		//面试题2:描述下列代码会创建几个String对象
		//答案:3个,"abc" + new出来的两个对象
//		String str1 = new String("abc");
//		String str2 = new String("abc");
		
	}
}
public class Test05 {
	/**
	 * 知识点:深入String - 拼接问题
	 * 
	 * 拼接规则:
	 * 		1.两个常量字符串拼接,在编译阶段就直接拼接
	 */
	public static void main(String[] args) {
		
		String str1 = "abc";
		String str2 = "abc";
		System.out.println(str1 == str2);//true
		
	
		String str3 = "ab" + "c";
		System.out.println(str1 == str3);//true
		
		final String s1 = "ab";
		final String s2 = "c";
		String str4 = s1 + s2;
		System.out.println(str1 == str4);//true
		
		String s3 = "ab";
		String s4 = "c";
		String str5 = s3+s4;//new StringBuilder(String.valueOf(s3)).append(s4).toString();
		System.out.println(str1 == str5);//false	
	}
}

5,StringBuffer和StringBuilder的深入

public class Test06 {
	/**
	 * 知识点:深入StringBuilder和StringBuffer -- 创建过程
	 * 
	 * 理解:
	 * 		StringBuilder代表可变的字符序列。
	 * 		StringBuilder称为字符串缓冲区
	 * 		它的工作原理是:预先申请一块内存,存放字符序列,如果字符序列满了,
	 * 					    会重新改变缓存区的大小,以容纳更多的字符序列。
	 * 		StringBuilder是可变对象,这个是String最大的不同
	 * 
	 * 		StringBuffer代表可变的字符序列。
	 * 		StringBuffer称为字符串缓冲区
	 * 		它的工作原理是:预先申请一块内存,存放字符序列,如果字符序列满了,
	 * 					    会重新改变缓存区的大小,以容纳更多的字符序列。
	 * 		StringBuffer是可变对象,这个是String最大的不同
	 * 
	 * 继承关系:
	 * 		class StringBuilder extends AbstractStringBuilder
	 * 		class StringBuffer extends AbstractStringBuilder
	 * 
	 */
	public static void main(String[] args) {
		
		//默认容量:16个长度的字符数组
		//StringBuilder sb = new StringBuilder();
		
		//自定义容量:32个长度的字符数组
		//StringBuilder sb = new StringBuilder(32);
		
		//容量:"abc".length() + 16
		//StringBuilder sb = new StringBuilder("abc");
		
		//---------------------------------------------------------
		
		//默认容量:16个长度的字符数组
		//StringBuffer sb = new StringBuffer();
		
		//自定义容量:32个长度的字符数组
		//StringBuffer sb = new StringBuffer(32);
	
		//容量:"abc".length() + 16
		//StringBuffer sb = new StringBuffer("abc");
	}
}
public class Test07 {
	/**
	 * 知识点:深入StringBuilder和StringBuffer -- 底层原理
	 * 
	 * 小结:
	 * 		StringBuilder和StringBuffer底层都是依赖于共同的父类AbstractStringBuilder
	 * 		StringBuilder和StringBuffer的扩容机制:(value.length << 1) + 2;
	 * 		StringBuilder是线程不安全的,单个线程下使用
	 * 		StringBuffer是线程安全的,因为加锁,多线程下使用
	 */
	public static void main(String[] args) {
		
		StringBuilder sb1 = new StringBuilder();
		sb1.append("abc");
		System.out.println(sb1);
		
		StringBuffer sb2 = new StringBuffer();
		sb2.append("abc");
		System.out.println(sb2);
		
		System.out.println("-----------------------------");
		
		MyStringBuilder my1 = new MyStringBuilder();
		my1.append("abc");
		System.out.println(my1);
		
		MyStringBuffer my2 = new MyStringBuffer();
		my2.append("abc");
		System.out.println(my2);
	}
//编写我们自己的StringBuilder父类
import java.util.Arrays;

abstract class MyAbstractStringBuilder {

	//缓存数组
	char[] value;//[' ',' ',' ',' ']
	//有效字符个数
	int count;
	
	MyAbstractStringBuilder() {
    }

	MyAbstractStringBuilder(int capacity) {
        value = new char[capacity];
    }
	
	//获取有效字符的长度
    public int length() {
        return count;
    }

    //获取缓存数组的长度
    public int capacity() {
        return value.length;
    }
    
    //添加数据 str - "abc"
    public MyAbstractStringBuilder append(String str) {
    	//判断数据是否为null
        if (str == null)
            return appendNull();//添加null数据的情况 - 把null的四个字符添加到缓存数组中
        
        int len = str.length();
        ensureCapacityInternal(count + len);
        
        str.getChars(0, len, value, count);//(开始下标-包含,结束下标-排他,目标数组,偏移量)
        count += len;
        return this;
    }
    
    //添加null值
    private MyAbstractStringBuilder appendNull() {
        int c = count;//0
        ensureCapacityInternal(c + 4);//4
        final char[] value = this.value;//['n','u','l','l']
        value[c++] = 'n';
        value[c++] = 'u';
        value[c++] = 'l';
        value[c++] = 'l';
        count = c;
        return this;
    }
    
    //minimumCapacity - 4
    private void ensureCapacityInternal(int minimumCapacity) {

    	//4-0 > 0
        if (minimumCapacity - value.length > 0) {
            value = Arrays.copyOf(value,newCapacity(minimumCapacity));
        }
    }
    
    //缓存数组最大长度
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    
    //minCapacity - 4
    private int newCapacity(int minCapacity) {
        
    	//newCapacity - 2
        int newCapacity = (value.length << 1) + 2;//扩容机制
        
        //2 - 4 < 0
        if (newCapacity - minCapacity < 0) {
        	//newCapacity - 4
            newCapacity = minCapacity;
        }
        return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)
            ? hugeCapacity(minCapacity)
            : newCapacity;
    }
    
    private int hugeCapacity(int minCapacity) {
        if (Integer.MAX_VALUE - minCapacity < 0) { // overflow
            throw new OutOfMemoryError();//报错 -- 内存溢出的错误
        }
        return (minCapacity > MAX_ARRAY_SIZE)
            ? minCapacity : MAX_ARRAY_SIZE;
    }
    
    @Override
    public String toString() {
    	return String.valueOf(value);
    }
}
//继承父类使用其方法
public class MyStringBuffer extends MyAbstractStringBuilder{
	
	public MyStringBuffer() {
		super(16);
	}
	
	public MyStringBuffer(int capacity) {
		super(capacity);
	}
	
	public MyStringBuffer(String str) {
		super(str.length() + 16);
		this.append(str);
	}
	
	//StringBuffer 的append方法是线程安全的---synchronized 
	@Override
	public synchronized MyStringBuffer append(String str) {//上锁
		super.append(str);
		return this;
	}//解锁

}
//同上
public class MyStringBuilder extends MyAbstractStringBuilder{
	
	public MyStringBuilder() {
		super(16);
	}
	
	public MyStringBuilder(int capacity) {
		super(capacity);
	}
	
	public MyStringBuilder(String str) {
		super(str.length() + 16);
		this.append(str);
	}
	
	//StringBuilder 的append方法不是线程安全的
	@Override
	public MyStringBuilder append(String str) {
		super.append(str);
		return this;
	}

}

二,关于时间日期的类

1,Date类–日期类

import java.util.Date;

public class Test01 {
	/**
	 * 知识点:关于日期时间的类
	 * 		Date(java.util)		日期类
	 * 		SimpleDateFormat	格式化日期类
	 * 		Calendar			日历类
	 */
	public static void main(String[] args) {
		
		//Date date = new Date();
		
		//星期 月份 日期 时:分:秒 时区 年份
		//Fri Dec 15 14:15:45 CST 2023
		//System.out.println(date);
		
		//Thu Jan 01 08:00:00 CST 1970
		Date date = new Date(1000);
		System.out.println(date);
		
	}
}

2,SimpleDateForma–格式化日期类

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

public class Test02 {
	/**
	 * 知识点:关于日期时间的类
	 * 		Date(java.util)		日期类
	 * 		SimpleDateFormat	格式化日期类
	 * 		Calendar			日历类
	 */
	public static void main(String[] args) throws ParseException {
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
	
		//将日期对象格式化成字符串
		String datetime = sdf.format(new Date());
		System.out.println(datetime);
		
		//将字符串解析成日期对象
		Date date = sdf.parse("2023年12月15日 14:65:57");
		System.out.println(date);
	}
}

3,Calendar–日历类

import java.util.Calendar;

public class Test03 {
	/**
	 * 知识点:关于日期时间的类
	 * 		Date(java.util)		日期类
	 * 		SimpleDateFormat	格式化日期类
	 * 		Calendar			日历类
	 */
	public static void main(String[] args) {
		
		//获取日历的实例化对象
		Calendar c = Calendar.getInstance();
	
		//获取信息
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH) + 1;
		int day = c.get(Calendar.DAY_OF_MONTH);
		int hour = c.get(Calendar.HOUR);
		int minute = c.get(Calendar.MINUTE);
		int second = c.get(Calendar.SECOND);
		
		System.out.println(year);
		System.out.println(month);
		System.out.println(day);
		System.out.println(hour);
		System.out.println(minute);
		System.out.println(second);
	}
}

三,math类–数学类

public class Test01 {
	/**
	 * 知识点:Math - 数学类
	 * 
	 * 	Math类提供了一序列基本数学运算和几何函数的方法。
	 * 	Math类是final类,并且它的所有成员变量和成员方法都是静态的。
	 */
	public static void main(String[] args) {
		
		System.out.println("求次方:" + Math.pow(3, 2));//9.0
		System.out.println("求平方根:" + Math.sqrt(9));//3.0
		System.out.println("求绝对值:" + Math.abs(-100));//100
		System.out.println("向上取整(天花板):" + Math.ceil(1.1));//2.0
		System.out.println("向下取整(地板):" + Math.floor(1.9));//1.0
		System.out.println("四舍五入:" + Math.round(1.5));//2
		System.out.println("最大值:" + Math.max(10,20));//20
		System.out.println("最小值:" + Math.min(10,20));//10
		System.out.println("随机数(0包含~1排他):" + Math.random());
		
		//需求:随机出1~100的数字
		int num = (int)(Math.random()*100) + 1;
		System.out.println(num);
	}
}
public class Test02 {
	/**
	 * 知识点:Math - 数学类
	 */
	public static void main(String[] args) {
		
		//面试题:Math的abs()有可能出现负数吗?
		System.out.println(Math.abs(-100));
		
		System.out.println(Integer.MAX_VALUE);//2147483647 -- 2的31次方-1
		System.out.println(Integer.MIN_VALUE);//-2147483648 -- -2的31次方
		
		System.out.println(Math.abs(Integer.MIN_VALUE));
		System.out.println(Math.abs(Integer.MAX_VALUE + 1));
	}
}

四,Random–随机类

import java.util.Random;

public class Test01 {
	/**
	 * 知识点:Random - 随机类
	 */
	public static void main(String[] args) {
		
		Random ran = new Random();
		
		System.out.println("随机出int类型取值范围里的数据:" + ran.nextInt());
		System.out.println("随机出float类型取值范围里的数据:" + ran.nextFloat());
		System.out.println("随机出double类型取值范围里的数据:" + ran.nextDouble());
		System.out.println("随机出boolean类型取值范围里的数据:" + ran.nextBoolean());
		System.out.println("随机出0~9的int数据:" + ran.nextInt(10));
	}
}

1,点名器

import java.util.Random;

public class Test02 {
	/**
	 * 知识点:Random - 点名器
	 */
	public static void main(String[] args) {
		
		String[] names = {"张偲","徐灿","彭鹏","杨彩虹","刘婷婷","周隽乐","严荐翔"};
		
		Random random = new Random();
		int index = random.nextInt(names.length);
		System.out.println(names[index]);
		
	}
}

2.验证码

		//随机生成6位数的验证码----伪代码
		Random ra=new Random();
		String[] name=new String[]{"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"};
		StringBuffer sb=new StringBuffer();
		for (int i = 0; i < 6; i++) {
			int t=ra.nextInt(name.length);
			sb.append(name[t]);
		}
		System.out.println(sb);

3,扩展–种子数


import java.util.Random;

public class Test03 {
	/**
	 * 知识点:Random - 种子数
	 * 
	 * 注意:种子数固定,随机出的数字就是固定的!!!
	 */
	public static void main(String[] args) {
		
//		Random random = new Random(1000);
//		System.out.println(random.nextInt());//-1244746321
		
		Random random = new Random();
		System.out.println(random.nextInt());
		System.out.println(random.nextInt(10));
	
		System.out.println("---------------------");
		
//		MyRandom myRandom = new MyRandom(1000);
//		System.out.println(myRandom.nextInt());
		
		MyRandom myRandom = new MyRandom();
		System.out.println(myRandom.nextInt());
		System.out.println(myRandom.nextInt(10));
	}
}
public class MyRandom {
	
	private long seed;//种子数
	
	public MyRandom() {
		this(seedUniquifier() ^ System.nanoTime());
	}

	public MyRandom(long seed) {
		this.seed = seed;
	}

	private static long seedUniquifier() {
        for (;;) {
            long current = System.currentTimeMillis();//获取自1970年1月1日0:0:0到现在的毫秒值
            long next = current * 181783497276652981L;
            if (next%3==0 || next%17==0 || next%4==0)
                return next;
        }
    }
	
	public int nextInt(){
		return (int) seed;
	}
	
	public int nextInt(int i){
		return Math.abs((int) seed) % i;
	}
}

五,正则表达式

public class Test01 {
	/**
	 * 知识点:正则表达式
	 * 含义:用来描述或者匹配一系列符合某个语句规则的字符串
	 * 
	 * 需求:替换一段字符串中的电话号码
	 * 
	 * 小结:正则表达式可以替换字符串
	 */
	public static void main(String[] args) {
		
		String str = "小红13990022101 小绿15196677229";
		
		//3 - 4 - 4
		String regex = "(1\\d{2})(\\d{4})(\\d{4})";
		
		//替换字符串,保留正则表达式中的第一组和第三组数据
		str = str.replaceAll(regex, "$1****$3");
		System.out.println(str);
	}
}

public class Test02 {
	/**
	 * 知识点:正则表达式
	 * 含义:用来描述或者匹配一系列符合某个语句规则的字符串
	 * 
	 * 需求:验证QQ邮箱
	 * 
	 * 小结:正则表达式可以验证字符串
	 */
	public static void main(String[] args) {
		
		String emial = "[email protected]";
		
		String regex = "\\d{5,10}@qq.com";
		
		//验证字符串是否符合正则表达式
		boolean matches = emial.matches(regex);
		System.out.println(matches);
	}
}

public class Test03 {
	/**
	 * 知识点:正则表达式
	 * 含义:用来描述或者匹配一系列符合某个语句规则的字符串
	 * 
	 * 需求:分割字符串
	 * 
	 * 小结:正则表达式可以分割字符串
	 */
	public static void main(String[] args) {
		
		String str = "C:\\资源\\日韩\\波多野结衣.avi";
		
		String regex = ":?\\\\";
		
		//依据正则表达式分割字符串
		String[] split = str.split(regex);
		for (String string : split) {
			System.out.println(string);
		}
	}
}

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test04 {
	/**
	 * 知识点:正则表达式
	 * 含义:用来描述或者匹配一系列符合某个语句规则的字符串
	 * 
	 * 需求:爬数据
	 * 
	 * 小结:正则表达式可以爬数据
	 */
	public static void main(String[] args) {
		
		String str = "
"; String regex = "]*\\bsrc\\b\\s*=\\s*('|\")?([^'\"\n\r\f>]+(\\.jpg|\\.bmp|\\.eps|\\.gif|\\.mif|\\.miff|\\.png|\\.tif|\\.tiff|\\.svg|\\.wmf|\\.jpe|\\.jpeg|\\.dib|\\.ico|\\.tga|\\.cut|\\.pic)\\b)[^>]*>"; //获取正则表达式对象 Pattern pattern = Pattern.compile(regex); //获取匹配结果 Matcher matcher = pattern.matcher(str); //遍历匹配结果 while(matcher.find()){ //获取匹配结果 String group = matcher.group(2);//2表示匹配结果中的第2个组别(小括号) System.out.println(group); } } }

六,Runtime–运行时环境类

public class Test01 {
	/**
	 * 知识点:Runtime - 运行时环境类
	 */
	public static void main(String[] args) {
		
		Runtime runtime = Runtime.getRuntime();
		
		System.out.println("获取系统的处理数:" + runtime.availableProcessors());//8
		System.out.println("获取最大内存数(字节):" + runtime.maxMemory());
		System.out.println("获取闲置内存数(字节):" + runtime.freeMemory());
	}
}

七,System–系统类

import java.io.InputStream;
import java.io.PrintStream;
import java.util.Scanner;

public class Test01 {
	/**
	 * 知识点:System(系统类) - 属性
	 */
	public static void main(String[] args) {

		//系统标准的输入流(方向:控制台->程序)
		InputStream in = System.in;
		Scanner scan = new Scanner(in);
		
		String next = scan.next();

		//系统标准的输出流(方向:程序->控制台)
//		PrintStream out = System.out;
//		out.println(next);
	
		//系统标准的错误输出流(方向:程序->控制台)
		PrintStream err = System.err;
		err.println(next);
		
		scan.close();
	}
}
public class Test02 {
	/**
	 * 知识点:System(系统类) - out和err的区别
	 * 
	 * out和err是两个线程的代码,多线程必须抢CPU资源,谁抢到了就执行谁
	 */
	public static void main(String[] args) {

		System.out.println("小明");
		System.err.println("小红");
		System.out.println("小强");
		
	}
}
import java.util.Properties;

public class Test03 {
	/**
	 * 知识点:System(系统类) -- 方法
	 */
	public static void main(String[] args) {
		
		//获取自1970年1月1日 到现在的毫秒数
		long currentTimeMillis = System.currentTimeMillis();
		System.out.println("获取毫秒:" + currentTimeMillis);

		//获取系统参数
		Properties properties = System.getProperties();
		System.out.println(properties);
		
		//通过键获取参数值
		String value = System.getProperty("os.name");
		System.out.println(value);
		
		//退出当前虚拟机 0-表示正常退出
		System.exit(0);
		
	}
}

八,扩展

public class Test01 {
	/**
	 * 扩展:频繁的字符串拼接使用StringBuilder或StringBuffer
	 */
	public static void main(String[] args) {
		
//		Runtime run = Runtime.getRuntime();
//		long startTime = System.currentTimeMillis();
//		long starMemory = run.freeMemory();
//		String str = "杨彩虹";
//		for (int i = 1; i <= 50000; i++) {
//			str += "小可爱,皇冠给你带";
//			//str = str + "小可爱,皇冠给你带";
//			//str = new StringBuilder(String.valueOf(str)).append("小可爱,皇冠给你带").toString();
//		}
//		long endMemory = run.freeMemory();
//		long endTime = System.currentTimeMillis();
//		
//		System.out.println("消耗时长:" + (endTime-starTime));//6358
//		System.out.println("消耗内存:" + (startMemory-endMemory));//-182381488
		
		Runtime run = Runtime.getRuntime();
		long starTime = System.currentTimeMillis();
		long startMemory = run.freeMemory();
		StringBuffer sb = new StringBuffer(460000);//减少扩容次数
		sb.append("杨彩虹");
		for (int i = 1; i <= 50000; i++) {
			sb.append("小可爱,皇冠给你带");
		}
		long endMemory = run.freeMemory();
		long endTime = System.currentTimeMillis();
		
		System.out.println("消耗时长:" + (endTime-starTime));//5
		System.out.println("消耗内存:" + (startMemory-endMemory));//920016
		
	}
}

//静态导入:将导入类中所有的静态属性和静态方法都变为当前类的静态属性和静态方法
import static java.lang.Math.*;

public class Test02 {
	/**
	 * 扩展:静态导入
	 * 
	 * 缺点:可读性太差
	 */
	public static void main(String[] args) {
		
		System.out.println(max(10, 20));
		System.out.println(min(10, 20));
		System.out.println(abs(-100));
	}
	
	public static int abs(int i){
		return 123456;
	}
}

你可能感兴趣的:(java,开发语言)