JAVA编程学习记录(API标准类库:工具类)
发布日期:2021-07-23 18:13:31 浏览次数:4 分类:技术文章

本文共 10226 字,大约阅读时间需要 34 分钟。

第六周 API标准类库:工具类

一 Arrays

Arrays: 针对数组操作的工具类,提供了一些针对数组排序的方法和二分搜索法

常用方法

public static String toString(int[] a):可以将int类型的数组转换成字符串 ([元素1,元素2,元素3...])

可以将各种数据类型的数组转为String类型;

package ArraysTest;import java.util.Arrays;public class ArraysDemo {	public static void main(String[] args) {		int[] arr = { 1, 3, 4, 5, 6 };		String str = Arrays.toString(arr);		System.out.println(str);		String[] arr1 = { "a", "b", "c" };		String str1 = Arrays.toString(arr1);		System.out.println(str1);	}}

public static void sort(int[] a)对指定的 int 型数组按数字升序进行排序

package ArraysTest;import java.util.Arrays;public class ArraysDemo {	public static void main(String[] args) {		// 定义数组,静态初始化一些内容		int[] arr = { 22,55,11,77,55,88 };		// 排序		Arrays.sort(arr);		// 转字符串输出		System.out.println(Arrays.toString(arr));//[11, 22, 55, 55, 77, 88]				// 定义字符数组		char[] ch = {'c','a','b'};		// 排序		Arrays.sort(ch);		// 输出		System.out.println(ch);//abc		System.out.println(Arrays.toString(ch));//[a, b, c]	}}

public static int binarySearch(int[] a,int key):二分搜索法: 在int类型的数组中查找key元素的索引

package ArraysTest;import java.util.Arrays;public class ArraysDemo {	public static void main(String[] args) {		// 定义数组,静态初始化一些内容		int[] arr = { 22,55,11,77,55,88 };		// 排序		Arrays.sort(arr);		// 查找元素55的位置		int index = Arrays.binarySearch(arr, 55);		// 输出位置		System.out.println(index);// 2				// 定义字符数组		char[] ch = {'c','a','b'};		// 排序		Arrays.sort(ch);		// 查找字符a的位置		int index1 = Arrays.binarySearch(ch, 'a');		// 输出位置		System.out.println(index1);// 0		}}
两个方法的源码分析

int[] arr = {24,69,80,57,13}

public static String toString(int[] a)toString(int[] a)的源码

//以后在实际开发中,只要有引用类型,在对引用类型数据进行操作的时候,对引用类型的对象进行非空判断;防止空指针异常(NullPointerException)

public static String toString(int[] a) {        if (a == null) //对数组进行非空判断            return "null";        int iMax = a.length - 1; //arr.length-1   //a--->arr        if (iMax == -1)            return "[]";        StringBuilder b = new StringBuilder();  //创建了一个字符串缓冲区        b.append('[');			//先追加了左中括号:[        for (int i = 0; ; i++) {            b.append(a[i]);		//给缓冲区中追加数组中的元素            if (i == iMax)                return b.append(']').toString();	//返回并且并追加了右中括号:]并且将数据元素转换字符串            b.append(", ");							//如果不是最后一个索引,那么中间追加逗号                        //if(i == iMax){            //	 return b.append(']').toString();            //}else{            	// b.append(", ");            //}        }    }

public static int binarySearch(int[] a,int key)的源码:

public static int binarySearch(int[] a, int key) {//a--->查找的数组	key--->要查找的数据        return binarySearch0(a, 0, a.length, key);    }        /**    	a--->arr:指定的int类型的数组    	fromIndex:指定索引开始:0    	toIndex:arr.length 5     	key:577    */    	nt[] arr = {13,24,57,69,80} ;     private static int binarySearch0(int[] a, int fromIndex, int toIndex,                                     int key) {        int low = fromIndex;     //最小索引        int high = toIndex - 1;//  最大索引  4        while (low <= high) { //如果最小索引小于=最大索引              int mid = (low + high) >>> 1;  >>> :无符号右移动(位运算符)    //中间索引:mid = 2 ,3 ,4             								位^:位异或            								位&:位与            								位|:位或            								<< :左移动            								有符合的数据表示法(原码,反码,补码)            								计算机底层运算数据的时候:通过补码进行运算的            int midVal = a[mid];		//	查找中间索引对应的元素:arr[2] = 57   69  80             if (midVal < key)			//判断:中间索引对应的元素 < key =577                low = mid + 1;		//low = mid + 1;   mid = (取到最大的mid的值) 4+1 = 5             else if (midVal > key)                high = mid - 1;            else                return mid; // key found        }        return -(low + 1);  // key not found.    // return  -(low+1) = -6    }

二 Calendar类:日历类

Calendar类是一个抽象类,它为特定瞬间与一组诸如 YEAR、MONTH、DAY_OF_MONTH、HOUR 等日历字段之间的转换提供了一些方法,并为操作日历字段(例如获得下星期的日期)提供了一些方法;

是一个抽象类,如何实例化?

    Calendar rightNow = new Calendar() ; 不能实例化

public static Calendar getInstance() :通过一个静态功能来创建日历对象 

    Calendar rightNow = Calendar.getInstance() ;

两个常用方法

public abstract void add(int field,int amount)根据日历的规则,为给定的日历字段添加或减去指定的时间量(常用

public int get(int field)返回给定日历字段的值

package CalendarTest;import java.util.Calendar;public class CalendarDemo {	public static void main(String[] args) {		// 创建方法创建Calendar类对象		Calendar c = Calendar.getInstance();		int year = c.get(Calendar.YEAR);		int month = c.get(Calendar.MONTH);// 默认初始月份为January,值为0,所以输出月份时要给值+1		int date = c.get(Calendar.DATE);		int week = c.get(Calendar.WEEK_OF_YEAR);		// 当前时间		System.out.println(year+"年"+(month+1)+"月"+date+"日"+"第"+week+"周");				// 输出5年后的10天前		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+"日");				}}

public final void set(int year, int month,int date)设置日历字段 YEAR、MONTH 和 DAY_OF_MONTH 的值

c.set(2022, 6, 10);				year = c.get(Calendar.YEAR);		month = c.get(Calendar.MONTH);		date = c.get(Calendar.DATE);		System.out.println(year+"年"+(month+1)+"月"+date+"日");//2022年7月10日
练习
package CalendarTest;/** * 需求:获取任意一年的二月有多少天  (改进:键盘录入一个年份) * 分析: *	1)键盘录入任意一个年份 *	2)创建日历类对象 *	3)设置年月日 *		set(录入year,2,1) ; //实际是3月1日 *	4)再利用add(int field,int amount) : 在这里只需要将日期往前退一天即可 */import java.util.Calendar;import java.util.Scanner;public class CalendarTest {	public static void main(String[] args) {		// 键盘录入对象		Scanner sc = new Scanner(System.in);		System.out.println("请输入年份");		int year = sc.nextInt();				//创建日历类对象		Calendar c = Calendar.getInstance();		// 设置为该年的三月一日		c.set(year, 2, 1);		// 给日期减一,即将日期往前推一天,则date为该年二月的最后一天		c.add(Calendar.DATE, -1);		// 输出天数		System.out.println("这一年的二月有"+c.get(Calendar.DATE)+"天");	}}

三  System类

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

常用方法:

public static void gc()运行垃圾回收器。 

System.gc();

public static void exit(int status)终止当前正在运行的 Java 虚拟机。参数用作状态码;一般情况,需要终止Jvm,那么参数0;

System.exit(0);

public static long currentTimeMillis()返回以毫秒为单位的当前时间

long time = System.currentTimeMillis();		System.out.println(time);

该方法单独使用没有意义,常用来测试代码执行效率

package System类;public class SystemDemo {	public static void main(String[] args) {		long star = System.currentTimeMillis();		for (int i = 0; i < 1000; i++) {			System.out.println("hello" + i);		}		long end = System.currentTimeMillis();		System.out.println("共耗时" + (end - star) + "毫秒");	}}

四  Date类

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

构造方法

public Date( )表示分配它的时间(精确到毫秒)

public Date(long date): 创建一个日期对象,指定毫秒值

常用方法

public void setTime(long time): 设置毫秒值

public long getTime()将Date--->long的毫秒值

package Date类;import java.util.Date;public class DateDemo {		public static void main(String[] args) {		// 创建日期类对象		Date d = new Date();		long time = d.getTime();		System.out.println(time);// 1526522751633		System.err.println(System.currentTimeMillis());// 1526522751633	}}

重点:Date的日期格式和日期的文本格式:String类型 之间进行转换

Date---->String(格式化)    String-->Date(解析)

中间的转换:使用一个中间类:DateFormat,并且DateFormat是一个抽象类,抽象意味着不能实例化,所以应该考虑用它的子类:SimpleDateFormat

SimpleDateFormat 是一个以与语言环境有关的方式来格式化和解析日期的具体类。它允许进行格式化(日期 -> 文本)、解析(文本 -> 日期)和规范化。

SimpleDateFormat的构造方法:

public SimpleDateFormat(String pattern) 根据pattern(模式:规则)构造一个SimpleDateFormat对象

    //SimpleDateFormat sdf = new SimpleDateFormat("xxx年xx月xx日") ;

日期和时间模式

年:yyyy

月:MM

日:dd

时:hh

分:mm

秒:ss

实际开发中:牵扯时间的东西,经常Date--String  String--Date

Date-->String

package Date类;import java.text.SimpleDateFormat;import java.util.Date;public class DateDemo {		public static void main(String[] args) {		// 创建日期类对象		Date d = new Date();		// 创建SimpleDateFormat类对象		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");				String str = sdf.format(d);		System.out.println(str);		}}

String-->Date

public Date parse(String source):解析

package Date类;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class DateDemo2 {	public static void main(String[] args) throws ParseException {		String sDate = "2018-10-1";		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");		// 注意 :simpleDateFormat在解析文本格式的时候,里面的模式(规则)一定要和文本格式的模式一致,否则就出现PareseException		// SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日");//		// java.text.ParseException		Date d = sdf.parse(sDate);		System.out.println(dd);	}}
练习

键盘录入你的出生年月日,算一下你来到这个世界多少天? (改进,输出多少岁)

package Date类;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Scanner;public class DateDemo2 {		public static void main(String[] args) throws ParseException {			// 创建键盘录入对象		Scanner sc = new Scanner(System.in);		System.out.println("请输入出生年月日yyyy-MM-dd:");		String str = sc.nextLine();				// 创建SimpleDateFormat对象		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");		// 创建日期类对象		Date date = sdf.parse(str);				// 获取出生年月所在的系统时间		long oldTime = date.getTime();		// 获取当前系统时间毫秒值		long newTime = System.currentTimeMillis(); 				long time = newTime - oldTime;				long day = time/1000/60/60/24;		long year = day/365;				System.out.println("你今年"+year+"岁,来到世上已经有"+day+"天了");	}}

五  Math类

Math 类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数。

常用方法:

public static int abs(int a):绝对值

System.out.println(Math.abs(-10));System.out.println(Math.abs(10));

public static double ceil(double a):向上取整

System.out.println(Math.ceil(12.34));//13.0

public static double floor(double a):向下取整

System.out.println(Math.floor(12.34));//12.0

public static int max(int a,int b):求最大值

System.out.println(Math.max(10, 20));//20

public static int min(int a,int b):求最小值

System.out.println(Math.min(Math.min(10, 30), 20));//10-->方法嵌套

public static double pow(double a,double b):a的b次幂

System.out.println(Math.pow(2.0, 10.0));// 1024.0

public static double random()返回带正号的 double 值,该值大于等于 0.0 且小于 1.0

System.out.println(Math.random());

public static int round(float a):四射五入

System.out.println(Math.round(12.56)+"---"+Math.round(12.46));// 13---12

public static double sqrt(double a):一个数的正平方根

System.out.println(Math.sqrt(1024));// 32

面试题:两个变量,让他们的值进行互换

int a = 6;		int b = 9;		// 实际开发中:中间变量的方式进行互换		// 位^的特点:一个数据被另一个数据位^两次,其值是它本身		a = a^b;		b = a^b; // b = a^b^b;		a = a^b;				System.out.println(a+","+b);

六  Random类

Random是一个可以获取随机数的类

构造方法:

public Random( ):无参构造

public Random(long seed):指定long类型的数据进行构造随机数类对象

常用方法:

public int nextInt(): 获取随机数,范围是int类型的范围2147483647-->-2147483648

Random r = new Random();	System.out.println(r.nextInt());

public int nextInt(int n):获取随机数,它的范围是在[0,n)之间

Random r = new Random();	System.out.println(r.nextInt(10));

七  正则表达式Pattern

转载地址:https://blog.csdn.net/otmqixi/article/details/80257412 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:JAVA编程学习记录(集合2)
下一篇:JAVA编程学习记录(API常用类(二))

发表评论

最新留言

关注你微信了!
[***.104.42.241]2024年03月28日 08时56分12秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章

java中哪个接口可以启用比较功能,Java集合知识测试--A卷 2019-04-21
php文章列表无限往下加载,给 Elementor 文章列表模块添加视频弹出和无限加载效果... 2019-04-21
linux锁定内核和dtd,[原]用DTD规范XML文档 2019-04-21
调整cst时间 linux,修改Linux系统时间EDT改为CST 2019-04-21
linux内核文件结构,linux内核的目录文件结构--详细 2019-04-21
linux 卸载pppoe,Linux ADSL拨号上网 2019-04-21
linux mysql密码错误,解决linux下mysql密码错误的问题 2019-04-21
3t硬盘 xp_怎么让xp支持3T硬盘 2019-04-21
python的web抓取_带有请求的Python Web抓取-登录后 2019-04-21
kswapd0 挖矿_Linux kswapd0 进程CPU占用过高 2019-04-21
opengl绘制长方体线框_OpenGL 绘制应用纹理的矩形 2019-04-21
c-free显示运行程序错误怎么办_电脑蓝屏了怎么办?小白看这里! 2019-04-21
aop的实现原理_你必须要懂的 Spring:Aop 2019-04-21
4位先行进位电路 logisim_数字电路学习笔记(八):计算电路 2019-04-21
spyder怎么看已有的包_怎么样做一份好吃的羊肉手抓饭?看了包学会 2019-04-21
freebuds3怎么查激活日期_怎么查股票的月平均价格 中泰证券股票上市日期 2019-04-21
八类网线和七类网线的区别_七类网线的知识你知道多少? 2019-04-21
链接orientdb的图形数据库_血清标志物数据库推荐 2019-04-21
centos7建站php_有想法不会行动?想建站无从下手?看过来 2019-04-21
云联惠认证时间_2020.10.24号最新币圈动态资讯:piKYC延长时间,趣步,好玩吧,AOT慈善,蚂蚁短视频,猫爪,秀刻,BTD,GEC... 2019-04-21