Conversión de referencia detallada entre el envasado tipos y tipos de datos

A, String

una, características:
	--String字符串类,用来表示"",String类被final修饰,也就是不可以被继承。
	--String类底层维护了一个char[],而且是final的,也就是说数组一旦创建长度和值都不能被修改了,字符串就变成了一个常量。
	--源码摘抄:
		--public final class String{}
		--private final char value[];
b, crear un objeto:
	--String(char[] value) 分配一个新的 String,使其表示字符数组参数中当前包含的字符序列。
métodos c, comúnmente utilizados:
	--char charAt(int index)  返回指定索引处的 char 值。 
	--String concat(String str) 将指定字符串连接到此字符串的结尾。 
	--boolean contains(CharSequence s) 当且仅当此字符串包含指定的 char 值序列时,返回 true。 
d, prueba:
//这个类用来测试字符串使用
		public class Test1_String {
			public static void main(String[] args) {
				//1、创建字符串对象
				//String(char[] value) 分配一个新的 String,使其表示字符数组参数中当前包含的字符序列。
				char[] c = new char[10];
				String s = new String(c);//可以体现字符串底层维护了一个char[],存储在堆内存中。
				
				String s2 = "abc";//可以直接赋值,存储在堆内存的常量池中。
				
				//2、常用方法
				System.out.println(  s2.charAt(1) );//b//获取指定索引对应着的字符
				System.out.println(  s2.concat("mno") );//拼接字符串
				System.out.println(  s2.contains("bc")  );//判断是否包含执行字符串
				System.out.println(  s2.endsWith("opq")  );//判断是否以指定元素结束
				System.out.println(  s2.equals("abc")  );//比较了字符串存储的值本身,因为String类重写了equals()
				System.out.println(  s2.hashCode()  );//获取对象在内存中的哈希码值
				System.out.println(  s2.getBytes()   );//[B@15db9742
				System.out.println(  Arrays.toString(  s2.getBytes()  )  );//因为返回值是byte[]只存整型,[97, 98, 99]
				
				s2="abcaaaccc";
				System.out.println(  s2.indexOf("c"));//指定字符串在s2中第一次出现的位置
				System.out.println(  s2.lastIndexOf("c"));//指定字符串在s2中最后一次出现的位置
				System.out.println(  s2.isEmpty()  );//判断字符串是否为空
				System.out.println(  s2.length()  );//获取字符串的长度
				System.out.println( s2.startsWith("iop")  );//判断是否以指定内容开始
				System.out.println( s2.substring(3)  );//从指定下标处开始向后截取字符串[3,n)
				System.out.println( s2.substring(3,6)  );//从第一个下标开始,到第二个下标的结束,截取中间的字符串,含头不含尾[m,n)
				System.out.println(  s2.toCharArray()  );//toCharArray()返回值是一个char[]
				
				System.out.println(  s2.toLowerCase()  );//把s2都转小写
				System.out.println(  s2.toUpperCase()  );//把s2都转大写
				
				s2 = "    abc     ";
				System.out.println(  s2.trim() );//去除前面和后面的多余空格
				System.out.println( String.valueOf(100)  +1 );
				
				s2="a|b|c|d|e|f";
				//在java里有一些特殊的字符  \  | ,程序就无法完成你想要的功能,想要实现功能,需要对特殊字符转义\\
				String[] strs = s2.split("\\|");//按照指定的方式切割字符串
				System.out.println(  Arrays.toString(strs) );//[a, b, c, d, e, f]
				
			}
		}

二, StringBuilder

una, crear objetos
  • El StringBuilder () Construye una cadena sin generador de caracteres y una capacidad inicial de 16 caracteres.
b, un método común
  • append StringBuilder (String str) la cadena especificada a esta secuencia de caracteres.
c, Pruebas: la eficiencia Cadena de conexión
//这个类用来测试字符拼接时效率问题
//字符串在做大量的拼接时,使用原始的+拼接,效率极低。
//可以使用工具类StringBuilder / StringBuffer来优化字符串拼接过程。
//StringBuffer诞生于jdk1.0,StringBuilder诞生于jdk1.5。
public class Test2_StringBuilder {
	public static void main(String[] args) {
//		method();//用+拼接字符串,拼接10000次
		method1();//优化字符串拼接
	}
	private static void method1() {
		//定义字符串
		String str = "abcdefghijklmnopqrstuvwxyz" ;
		//拼接10000次字符串
//		StringBuilder sb = new StringBuilder();
		StringBuffer sb = new StringBuffer();
		long start = System.currentTimeMillis(); // 计时开始ms
		for (int i = 0; i < 10000; i++) {
			sb.append(str); // 拼接str
		}
		long end = System.currentTimeMillis(); // 计时结束ms
		//计时
		System.out.println(end-start);//3159ms    2ms
	}
	private static void method() {
		//定义字符串
		String str = "abcdefghijklmnopqrstuvwxyz" ;
		
		//拼接10000次字符串
		String result = "";//定义变量,记录拼接结果
		
		long start = System.currentTimeMillis(); // 计时开始ms
		
		for (int i = 0; i < 10000; i++) {
			result = result+str ;//拼接 result += str;
		}
		
		long end = System.currentTimeMillis(); // 计时结束ms
		
		//打印拼接结果
		System.out.println(end-start);//3159ms 3.2s
	}
}

En tercer lugar, el embalaje

un concepto:
  • Para los ocho tipos básicos han clase de contenedor correspondiente con el fin de proporcionar mejores características
    - los ocho tipos básicos: el byte Largo Corto int flotador carbonilla booleano Doble
    - clase contenedora: Byte entero corto a largo Flotador doble carácter de Boole
b, la estructura de clase de contenedor herencia:
	-- 所有的数字类型的父类 叫Number
		--源码摘抄:public abstract class Number
		-- byte byteValue() 以 byte 形式返回指定的数值。 
		--abstract  double doubleValue()  以 double 形式返回指定的数值。 
		--abstract  float floatValue()  以 float 形式返回指定的数值。 
		--abstract  int intValue()  以 int 形式返回指定的数值。 
		--abstract  long longValue()  以 long 形式返回指定的数值。 
		--short shortValue()   以 short 形式返回指定的数值。 
c, Integer
	--源码摘抄:public final class Integer
	--创建对象:
		--Integer(int value) 构造一个新分配的 Integer 对象,它表示指定的 int 值。
	--常用方法:
		--int intValue() 以 int 类型返回该 Integer 的值。 
		--static int parseInt(String s)将字符串参数作为有符号的十进制整数进行解析。
		--static Integer valueOf(int i)返回一个表示指定的 int 值的 Integer 实例。 
prueba:
//这个类用来测试包装类型:因为包装类能提供更丰富的功能
		public class Test3_Number {
			public static void main(String[] args) {
				//1、创建Integer对象
				//Integer是针对基本类型的int进行了包装
				Integer i = new Integer(10);  //普通的创建方式,效率稍低
				Integer i2 = Integer.valueOf(10);//效率高,在Integer类中,包含256个Integer缓存对象,范围是 -128到127。
		//使用valueOf()时,如果指定范围内的值,访问缓存对象,而不新建;如果指定范围外的值,直接新建对象。
				
				Integer i3 = Integer.valueOf(10);
				System.out.println( i2==i3 );//i2已经存过了10,i3又要存相同数据就不再开辟空间存相同数据了,而是直接拿着存过的10使用														
				System.out.println( i == i3 );
				
				//2、常用方法
				System.out.println(i2.MAX_VALUE);
				
				//3、i或者i2已经是把基本类型的10变成了包装类型了,怎么再把包装类型变回成基本类型?
				System.out.println(  i2.intValue() );
				
				int sum = Integer.parseInt("100");//4、把字符串类型的数字  转成 基本类型
				System.out.println( sum );
			}
		}
d, Doble
--就是基本类型double对应的包装类型,用来为double提供更丰富的功能。
--创建对象:
	--Double(double value)构造一个新分配的 Double 对象,它表示基本的 double 参数。	
	--static Double valueOf(double d) 返回表示指定的 double 值的 Double 实例。 
--常用方法:
	--double doubleValue()  返回此 Double 对象的 double 值。 
	--static double parseDouble(String s)返回一个新的 double--测试:

	package cn.tedu.number;
	//这个类用来测试包装类型:因为包装类能提供更丰富的功能
	public class Test3_Number {
		public static void main(String[] args) {
			//1、创建Integer对象
			//Integer是针对基本类型的int进行了包装
			Integer i = new Integer(10);  //普通的创建方式,效率稍低
			Integer i2 = Integer.valueOf(10);//效率高,在Integer类中,包含256个Integer缓存对象,范围是 -128到127。
	//使用valueOf()时,如果指定范围内的值,访问缓存对象,而不新建;如果指定范围外的值,直接新建对象。
			
			Integer i3 = Integer.valueOf(10);
			System.out.println( i2==i3 );//i2已经存过了10,i3又要存相同数据就不再开辟空间存相同数据了,而是直接拿着存过的10使用														
			System.out.println( i == i3 );
			
			//2、常用方法
			System.out.println(i2.MAX_VALUE);
			
			//3、i或者i2已经是把基本类型的10变成了包装类型了,怎么再把包装类型变回成基本类型?
			System.out.println(  i2.intValue() );
			
			int sum = Integer.parseInt("100");//4、把字符串类型的数字  转成 基本类型
			System.out.println( sum );
			
			//double  - Double
			//1、创建Double对象  -- 把基本类型变成包装类型
			Double d = new Double(3.14);
			Double d2 = Double.valueOf(3.14);
			
			//2、常用方法
			System.out.println(d2.MAX_VALUE);
			System.out.println(d2.doubleValue());//把包装类型的值变回成基本类型
			double count = Double.parseDouble("3.14");//把字符串类型的值变成基本类型
			System.out.println(count);
			
		}
	}

En cuarto lugar, la clase Fecha Fecha

un concepto
  • clase Date representa un momento específico, con una precisión de milisegundos
b, crear un objeto
  • Fecha () asignado fecha de objeto y lo inicializa el objeto para indicar su hora asignada (precisión de una milésima de segundo).
c, la prueba
//这个类用来测试日期类date
	public class Test4_Date {
		public static void main(String[] args) {
			//1,创建Date对象
			Date date = new Date();				
			//2,常用方法
			System.out.println( date.getDate() );//今天是当月的几号
			System.out.println( date.getDay() );//今天是星期几
			System.out.println( date.getHours() );//现在是几点
			System.out.println( date.getMonth() );//现在是几月,底层代码-1了 
			System.out.println( date.getMinutes() );//现在是每小时的哪一分钟
			System.out.println( date.getSeconds() );//现在是每分钟的哪一秒
			System.out.println( date.getTime() );//自1970-1-1 零点到现在的毫秒值
			System.out.println( date.getYear() );//从1900年到现在一共多少年了
			System.out.println( date.toLocaleString() );//变成当前的系统日期
			System.out.println( date.hashCode() );//对象在内存中的哈希码值
		}
	}

En quinto lugar, las herramientas fecha SimpleDateFormat

un concepto
  • Se utiliza para convertir entre la fecha de tipo fecha específica y la fecha de tipo String
b, crear un objeto
  • SimpleDateFormat (Patrón de encordado) con un patrón determinado y la fecha predeterminada formato de la configuración regional simbolo SimpleDateFormat.
c, el método utilizado
  • Formato (Fecha): la cadena con formato de fecha
  • parse (String): String analiza en la Fecha
d, calcular el número de días a sobrevivir:
//这个类用来测试  日期格式化工具类
	public class Test5_SimpleDate {
		public static void main(String[] args) throws ParseException {
			//1,接收用户输入的出生日期
			String birthday = new Scanner(System.in).nextLine();				
			//2,把String类型的日期 转成  Date类型
			//格式怎么要求呢?--y年M月d天数,格式如:2020-10-10
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//创建工具类的对象
			Date birth = sdf.parse(birthday);			
			//3,做时间差
			long start = birth.getTime();//获取出生日期那天,对应的ms
			long now = System.currentTimeMillis();//获取当前时间的ms				
			System.out.println(  (now-start)/1000/60/60/24  );//ms->天
		}
	}
Publicado 36 artículos originales · alabanza ganado 13 · vistas 1067

Supongo que te gusta

Origin blog.csdn.net/weixin_44598691/article/details/104771733
Recomendado
Clasificación