Java_常用类之包装类和其他类

常用类_包装类


1)每个基本类型都存在一个默认的包装类类型(引用类型);

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

3)将基本数据类型封装成对象的好处在于可以在对象中定义更多的功能方法操作该数据;

4)常用于基本数据类型与字符串之间的转换;

5)包装类实际上就是持有了一个基本类型的属性,作为数据的存储空间(Byte中有一个byte属性),还提供了常用的转型方法,以及常量,即可以存储值,又具备了一系列的转型方法和常用常量,比直接使用基本类型的功能更强大;

基本类型对应的包装类型:

  • int ----> Integer(多)
  • char ----> Character(多)
  • byte ----> Byte
  • short----> Short
  • long ----> Long (多)
  • float----> Float
  • double—> Double
  • boolean —>Boolean

1. Integer类

Integer类在对象中包装了一个基本类型Int的值;能在int和String之间互相转化。

1.1 Integer的静态功能

  • public static String toBinaryString(int i) :将整数数据转化为二进制数据
  • public static String toOctalString(int i) :将整数数据转化为八进制数据
  • public static String toHexString(int i) :将整数数据转化为十六进制数据
  • public static final int MAX_VALUE:表示int类型的能够表示的最大值
  • public static final int MIN_VALUE:表示int类型的能够表示的最小值
public static void main(String[] args) {
		//计算100对应的进制
		System.out.println(Integer.toBinaryString(100));//1100100
		System.out.println(Integer.toOctalString(100));//144
		System.out.println(Integer.toHexString(100));//64
		
		//int类型范围
		System.out.println(Integer.MIN_VALUE);//-2147483648
		System.out.println(Integer.MAX_VALUE);//2147483647
	}
}

1.2 Integer类的构造方法

  • public Integer(int value):把int类型的变量通过构造方法转换成Integer

  • public Integer(String s):把String类型的变量通过构造方法转换成Integer

public static void main(String[] args) {
		int value = 100;
    	//创建对象
		Integer i = new Integer(value);
		System.out.println(i);

		//传入的String类型的参数必须是一个数字型字符串
		String s = "123456";//必须是数字型字符串
		Integer integer = new Integer(s);
		System.out.println(integer);
	}
}

注:在使用字符串构建数字型包装类型对象时,要保证类型的兼容,否则产生NumberFormatException异常(数字格式化异常);

1.3 Int类型跟String类型的相互转化

  • int转化为String:首先将int转化为Integer再转化为String
  • String转化为int:首先将String转化为Integer再转化为int或者直接调用parseXXX方法

int转String:

public static Integer valueOf(int i)—>toString()转换

public static String toString(int i):Integer的静态toString(int i)

String转int:

public int intValue()

parseXXX(String s)字符串转成相关的包装类型,7种包装类型都有,除Character外;

  • parseInt(“123”);
  • parseIong(“123”);
  • parseByte(“123”);
public static void main(String[] args) {
		//int转String
		int i1 = 100;
		//1.空串拼接
		String s = "";
		System.out.println(s += i1);
		
		//2.public String toString()
		Integer i2 = new Integer(i1);
		String str = i2.toString();
		System.out.println(str);
		
		//3.public static String toString(int i)
		String str2 = Integer.toString(i1);
		System.out.println(str2);
		
		//4.public static Integer valueOf(int i)
		Integer integer = Integer.valueOf(i1);
		String str3 = integer.toString();
		System.out.println(str3);
		
		//String转int
		//1.String(数字字字符串)--->Integer --->int
		String s2 = "10";
		Integer i3 = new Integer(s2);
		int value1 = i3.intValue();
		System.out.println(value1);
		
		//2.public static int parseInt(String s):
		int value2 = Integer.parseInt(s2);
		System.out.println(value2);
	}
}

1.4 自动拆箱和装箱

JDK1.5后简化了定义方式提供自动装箱、拆箱,使得基本类型和包装类型自动转换,简化使用包装类的编程过程。

自动装箱:将基本类型赋值包装类型,调用valueOf(int i)(int---->Integer)

自动拆箱:将包装类型值直接赋值给基本类型调用intValue()(Integer—>int)

public static void main(String[] args) {
		//基本类型
		int i1 = 100;
		//包装类型
		Integer i2 = new Integer("200");
		Integer i3 = Integer.valueOf("300");
		
		//JDK1.5之后
		//自动装箱
		Integer i4 = 400;//基本类型给了对象
		
		//自动拆箱
		//int i5 = i4.intValue();简化为
		int i5 = i4;
		
		//使用基本类型没有方法只是属性,使用包装类型可以在调用属性的同时调用对应的方法
		Student s = new Student();
		int ii = s.age.sum(1, 2);//调用求和方法
		System.out.println(ii);
	}
}
class Student{
	String name;//包装类型
	Integer age;
	Double id;
}

注:使用基本类型没有方法只是属性,使用包装类型可以在调用属性的同时调用对应的方法;(代

码见上)

案例

Integer的地址问题

public static void main(String[] args) {
		Integer i1 = new Integer(100);
		Integer i2 = new Integer(100);
		System.out.println(i1 == i2);//false
		
		Integer i3 = new Integer(127);
		Integer i4 = new Integer(127);
		System.out.println(i3 == i4);//false
		
		Integer i5 = 127;//不开辟内存
		Integer i6 = new Integer(127);//new对象了,不看值
		System.out.println(i5 == i6);//false
		
		Integer i7 = 128;//超过范围了重新new Integer(128)
		Integer i8 = 128;
		System.out.println(i7 == i8);//false
		
		Integer i9 = 127;
		Integer i10 = 127;
		System.out.println(i9 == i10);//true
	}
}
  • Integer i = new Integer(int); 构造方法需要在堆内存中开辟空间

  • Integer i = 128;执行Integer的valueOf(int i) ;在int范围(-128~127)直接从缓冲区取,不在就会New对象,地址值就改变了;

2. Character类

Character 类在对象中包装一个基本类型 char 的值;

2.1 构造方法

public Character(char value) :把char类型的变量通过构造方法转换成Character

public static void main(String[] args) {
		//创建一个Character对象
		Character ch = new Character((char)97);//先转换
		Character ch1 = new Character('A');
		System.out.println(ch + "\t" +ch1);
		
	}
}

2.2 成员方法

Character类型的判断功能:

  • public static boolean isDigit(char ch):判断当前指定的字符是否数字字符
  • public static boolean isLowerCase(char ch):判断是否是小写字母字符
  • public static boolean isUpperCase(char ch):判断是否是大写字母字符

Character类型的转化功能:

  • public static char toLowerCase(char ch):转换成小写
  • public static char toUpperCase(char ch):转换成大写
public static void main(String[] args) {
		//判断是否是数字字符
		System.out.println("isDigit:" + Character.isDigit('0'));//true
		System.out.println("isDigit:"+Character.isDigit('a'));//false
		
		//判断是否是小写字符
		System.out.println("isLowerCase:" + Character.isLowerCase('A'));//false
		System.out.println("isLowerCase:"+Character.isLowerCase('a'));//true
		
		//判断是否是大写字符
		System.out.println("isUpperCase:" + Character.isUpperCase('A'));//true
		System.out.println("isUpperCase:"+Character.isUpperCase('a'));//false
    
   		 //转换成小写
		System.out.println("toLowerCase:" + Character.toLowerCase('A'));//a
		//转换成大写
		System.out.println("toUpperCase:" + Character.toUpperCase('a'));//A
	}
}

案例:Character成员方法的应用

键盘录入一个字符串,包含了大写字母字符,小写字母字符,数字字符?

public class CharacterTest {
	public static void main(String[] args) {
		int number = 0;
		int lower = 0;
		int upper = 0;
		
		Scanner sc = new Scanner(System.in);
		System.out.println("输入一个包含数字和字母的字符串:");
		String s = sc.next();
		
		//字符串转换为数组
		char[] c = s.toCharArray();
		for(int i = 0;i < c.length;i++){
			char ch = c[i];//就是一个字符
			if(Character.isUpperCase(ch)){
				upper++;
			}else if(Character.isLowerCase(ch)){
				lower++;
			}else if(Character.isDigit(ch)){
				number++;
			}
		}
		System.out.println("大写:" + upper + "个");
		System.out.println("小写:" + lower + "个");
		System.out.println("数字:" + number + "个");
	}
}

常用类_BigDecimal类


小数在计算机底层存储有有效数字的可能会出现精度的损失,所以就用到了BigDecimal类针对小数进行精确计算;

在java.math包中,用来精确计算的浮点数

BigDecimal bd = new BigDecimal(“1.0”);//构造方法

  • 加 BigDecimal add(BigDecimal bd);

  • 减 BigDecimal subtract(BigDecimal bd);

  • 乘 BigDecimal multiply(BigDecimal bd);

  • 除 BigDecimal divide(BigDecimal bd);

除不尽的情况下,必须明确保留几位小数位、是否使用四舍五入

public static void main(String[] args) {
		double d1 = 1.0;
		double d2 = 2.2 + 1.2;
		System.out.println(d1 == d2);//false
		System.out.println(2.2 + 1.2);//3.4000000000000004
		
		BigDecimal bd1 = new BigDecimal("2.2");
		BigDecimal bd2 = new BigDecimal("1.2");
		BigDecimal result1 = bd1.add(bd2);//3.4
		BigDecimal result2 = bd1.subtract(bd2);//1.0
		BigDecimal result3 = bd1.multiply(bd2);//2.64
		//除不尽的情况下,必须明确两个信息(保留几位小数位、是否使用四舍五入)
		//保留两位、超过一半的往上靠(四舍五入)
		BigDecimal result4 = bd1.divide(bd2 , 2 , BigDecimal.ROUND_HALF_UP);//1.83
		System.out.println(result1);
		System.out.println(result2);
		System.out.println(result3);
		System.out.println(result4);
	}
}

常用类_其他类


1. System类

System 类包含一些有用的类字段和方法,它不能实例化。

常用方法:

  • public static void gc():运行垃圾回收器,JVM 将未用的对象来回收掉,protected void finalize():和垃圾回收器gc有关系,当垃圾回收器确定不存在对该对象的更多引用时,由对象的垃圾回收器调用gc方法;

  • public static void exit(int status):终止当前正在运行的 Java 虚拟机 相当于break

  • public static long currentTimeMillis():获取当前系统时间的毫秒值,很少单独使用;

  • public static void arraycopy(Object src, int srcPos, Object dest,int destPos, int length):从一个数组中复制元素到另一个数组。

    Object src:原数组对象

    int srcPos:原数组中的某个索引值

    Object dest:目标数据对象

    int destPos:到目标数组中的某个角标结束进行复制

    int length:复制的长度

public static void main(String[] args) {
		int a = 10 ;
		System.out.println("a:"+a);
		System.exit(0); //终止Jvm了
		System.out.println("over");//不输出Over了,提前终止程序
		
    	//计算程序的耗时
		long start = System.currentTimeMillis() ;
		for(int x = 0 ; x < 10000; x ++) {
			System.out.println("hello"+x);
		}
		long end = System.currentTimeMillis() ;
		System.out.println("该程序耗时:"+(end-start)+"毫秒");
    
    	//定义两个数组
		int[] arr1 = {11,22,33,44,55} ;
		int[] arr2 = {66,77,88,99,10} ;
		//复制前
		System.out.println(Arrays.toString(arr1));//[11, 22, 33, 44, 55]
		System.out.println(Arrays.toString(arr2));//[66, 77, 88, 99, 10]
		
		//复制arr1数组中索引为1的元素,复制到arr2中以2为索引的地方,复制两个单位
		System.arraycopy(arr1, 1, arr2, 2, 2);
		System.out.println(Arrays.toString(arr1));//[11, 22, 33, 44, 55]
		System.out.println(Arrays.toString(arr2));//[66, 77, 22, 33, 10]
	}
}


2. Calendar类(了解)

Calender类是一个抽象类(不能实例化)为特定瞬间如YEAR、MONTH、DAY_OF_MONTH、HOUR 等日历字段之间的转换提供了一些方法,并为操作日历字段提供了一些方法。

2.1 成员方法

public static Calendar getInstance():通过方法进行实例化

public int get(int field) :通过指定的字段获取年月日

  • public static final int YEAR:获取年
  • public static final int MONTH:获取月,从角标为0开始取
  • public static final int DATE:获取日
public static void main(String[] args) {
		//创建日历类对象
		Calendar c = Calendar.getInstance() ;
    
		//获取年
		int year = c.get(Calendar.YEAR) ;
		//获取月
		int month = c.get(Calendar.MONTH) ; //从0开始(写 1月其实是2月)
		//获取月中的某一天
		int date = c.get(Calendar.DATE) ;
		System.out.println("当前时间为:"+year+"年"+(month+1)+"月"+date+"日");	
	}
}

public abstract void add(int field, int amount):给当前日历类的字段添加或者减去时间量

public final void set(int year, int month,int date):设置日历的年月日

public static void main(String[] args) {
    //创建日历类对象
    Calendar c = Calendar.getInstance();
    int year = c.get(Calendar.YEAR) ;
    int month = c.get(Calendar.MONTH) ;
    int date = c.get(Calendar.DATE) ;
    
    //5年后的十天前
    c.add(Calendar.YEAR, 5);
    c.add(Calendar.DATE, -10);
    //重新定义
    year = c.get(Calendar.YEAR) ;
    date = c.get(Calendar.DATE) ;
    System.out.println(year+"年"+(month+1)+"月"+date+"日");
	
    //设置时间
    c.set(2016, 5,25);
    year = c.get(Calendar.YEAR) ;
    month = c.get(Calendar.MONTH) ;
    date = c.get(Calendar.DATE) ;
    System.out.println(year+"年"+(month+1)+"月"+date+"日");
	}
}

3. Data,DataFormat类

Date类表示特定的瞬间,精确到毫秒。

3.1 常用方法:

Date() :通过该无参构造创建对象,表示分配的时间

Date(long time) :指定时间毫秒值 和1970年1月1日 零点零分零秒(一种计算方式)

public long getTime():获取指定的时间毫秒值

public static void main(String[] args) {
		//创建日期类对象
		Date date = new Date() ; //当前系统时间
		System.out.println(date);
    	
    	//指定时间的毫秒值
		long time1 = date.getTime() ;
		System.out.println(time1);//1592147626824
		//当前系统时间毫秒值(日期一般用data)
		System.out.println(System.currentTimeMillis()); //1592147626842
    
		//据1970年开始
		long time = 2000 * 60 * 600 ;
		//创建日期对象
		Date date2 = new Date(time) ;
		System.out.println(date2);//Fri Jan 02 04:00:00 CST 1970
	}
}

3.2 Data和String的转换

二者进行转换时需要使用DateFormat,是日期/时间格式化子类的抽象类,它以与语言无关的方式格式化并解析日期或时间。

不能通过DateFormat format = new DateFormat()实例化的;使用子类:SimpleDateFormat可以进行日期文本的相互转化

日期和时间模式:

  • y ---- > 年 ,如:2020用yyyy表示
  • M ---- > 月 ,如:5/05用MM表示
  • d ---- > 月中天,如:12/1 用dd表示
  • h---- > 小时
  • m---- > 分钟
  • s ---- > 秒

时间:2020年06月14日或者2020-06-14

模式:yyyy-MM-dd

构造方法:

  • SimpleDateFormat(String pattern):创建simpleDateFormat对象给定一种模式

  • public final String format(Date date):将一个Data格式化为日期/时间字符串

  • public Date parse(String source):解析,调用这个方法立马抛出一个解析异常(属于编译时器异常)

    注意:日期文本格式解析为Date日期 格式必须要保证SimpleDateFormat里面的参数模式和日期文本格式一致,否则出现简析异常;

public static void main(String[] args) throws ParseException{
		//Date----->String日期文本格式(格式化)
		//当前日期
		Date date = new Date() ;
		//创建SimpleDateFormat类给定一种模式
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd") ;
		//格式化
		String s = sdf.format(date) ;
		System.out.println(s);//"2020-06-14"
		
		//String 日期文本格式---->Date(模式格式要一致)
		String str = "2020-6-14" ;
		//需要SimpleDateFormat
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd") ;
		Date d = sdf2.parse(str) ;//解析报错,需要处理
		System.out.println(d);//Sun Jun 14 00:00:00 CST 2020
	}
}

4. Random类

用于产生随机数,java.util.Random包下的;

4.1 构造方法

构造方法:

  • Random():一般使用无参,新创建一个随机数生成器;

  • Random(long seed):long 种子创建一个新的随机数生成器,每次产生的随机数都是一样的,很少使用;

成员方法:

  • public int nextInt() :产生的随机数的范围是在int类型范围之内
  • public int nextInt(int n):产生的随机数的范围是在0-n之间,不包含n,如果要求0~n之间的随机数要在最后加1;
public static void main(String[] args) {
		//创建随机数生成器(无参)
		Random r = new Random();
		//产生10个数
		for(int i = 0; i < 10; i++){
			//随机产生100以内的随机数
			int number = r.nextInt(100)+1;//范围是0~100,不包含100所以要加1
			System.out.println(number);
		}
	}
}

注:产生一个随机数的两种方式:

  • Math类的 random()方法---->double [0.0,1.0)
  • Random类:无参构造+nextInt(int n)
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Willing卡卡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值