Java常用的实用类
1、String类
字符串就是一连串的字符序列,Java提供了String和StringBuffer两个类来封装字符串,并提出了一系列的方法来操作字符串对象。
-
java.lang.String类代表不可变的字符序列
1.1、String类常用构造器
1.String() //一个创建0个字符序列的String对象,并不是返回null。 String s1=new String(); System.out.println(s1); 2.String(byte[] bytes) //把字节数组转换成字符串。 byte[] by={98,99,100,101}; String s2 = new String(by); System.out.println(s2);//bcde 3.String(byte[] bytes,int offset,int length) //把一部分转换成字符串。 byte[] by1={98,99,100,101}; String s3=new String (by1,1,3); System.out.println(s3);//cde 4.String(char[] value) //把字符数组转换成字符串。 char[] chs1={'a','b',100,'e'}; String s4 = new String(chs,1,3); System.out.println(s4);//bde 5.String(char[] value,int offset,int count) //将指定的字符数组从offset开始,长度为count的字符原连缀成字符串。 char[] chs1={'a','b',100,'e'}; String s5 = new String(chs,1,3); System.out.println(s5);//bde 6.String(String original) //创建一个String对象为original的拷贝。
1.2、String类常用方法
public char charAt(int index) //返回字符串中第index个字符。 public int length() //返回字符串的长度。 public int indexOf(String str) //返回字符串中出现str的第一个位置 public int indexOf(String str,int fromIndex) //返回字符串中从fromIndex开始出现str的第一个位置 public boolean equals(string another) //比较字符串与another是否一样 public boolean equalsIgnoreCase(string another) //比较字符串与another是否一样(忽略大小写) public String replace(char oldChar,char newChar) //在字符串中用newchar字符替换oldchar字符 public boolean startswith(string prefix) //判断字符串是否以prefix字符串开头 public boolean endsWith(string suffix) //判断字符串是否以prefix字符串结尾 public string toUpperCase() //返回一个字符串为该字符串的大写形式 public String toLowerCase() //返回一个字符串为该字符串的小写形式 public String substring(int beginIndex) //返回该字符串从beginIndex开始到结尾的子字符串 public String substring(int beginIndex,int endIndex) //返回该字符串从beginIndex开始到endIndex结尾的子字符串 public Stringtrim() //返回将该字符串去掉开头和结尾空格后的字符串 public static String valueOf(...) //可以将基本数据类型数据转化为字符串 public String[] split(String regex) //可以将一个字符串按照指定的分隔符分割,返回分隔后的字符串数组。
2、日期和时间的显示形式
2.1、Date类
表示特定的瞬间,精确到毫秒(在java.util.Date包下)
构造方法:
public Date()
表示分配它的时间(精确到毫秒)。
public Date(long date):
创建一个日期对象,指定毫秒值 (需要将long 时间毫秒值转换成Date对象)
public void setTime(long time):
设置毫秒值
public long getTime()
将Date—>long的毫秒值
Date---->String(格式化) String–>Date(解析)
中间的转换:使用中一个中间类:DateFormat,并且DateFormat是一个抽象类,抽象意味着不能实例化,所以应该考虑用它的子类:
SimpleDateFormat 是一个以与语言环境有关的方式来格式化和解析日期的具体类。它允许进行格式化(日期 -> 文本)、解析(文本 -> 日期)和规范化。
2.2、SimpelDateFormat的构造方法:
public SimpleDateFormat(String pattern) //构造一个SimpleDateFormat对象,根据pattern(模式:规则)
SimpleDateFormat XXX = new SimpleDateFormat("xxx年xx月xx日") ;//需要抛出异常
simpleDateFormat在解析文本格式的时候,里面 模式(规则)一定要和文本格式的模式一直,否则就出现PareseException
日期和时间模式
年:yyyy 月:MM 日:dd
时:hh 分:mm 秒:ss
例子:
public final String format(Date date):格式化
Date d = new Date() ;
//创建SimpleDateFormat类对象
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String str = sdf.format(d) ;
public Date parse(String source):解析
String strDate = "yyyy-MM-dd" ;
//创建SimpleDateFormat类对象
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd") ;
//注意 :simpleDateFormat在解析文本格式的时候,里面 模式(规则)一定要和文本格式的模式一直,否则就出现PareseException
Date dd = XXX.parse(strDate) ;
2.3、Calendar类
定义:抽象类,获取日期和时间时考虑了时区问题
抽象类不能被实例化,需要调用静态方法getInstance()来创建Calendar对象后才能调用其它该类的其它方法:
Calendar calendar = Calendar.getInstance(); //创建一个代表系统当前日期的Calendar 对象
类变量:
Calendar.YEAR; //年
Calendar.MONTH; //月 ,从0开始
Calendar.DAY_OF_MONTH; //日
Calendar.HOUR; //小时
Calendar.MINUTE; //分钟
Calendar.SECOND; //秒
Calendar.MILLISECOND; //毫秒
成员方法:
成员方法中的field参数一般是Calendar类的字段
public void set(int year, int month, int date); // 设置Calendar对象的年月日时分秒字段
public void set(int field, int value); //给指定的Calendar字段赋值
public void get(int field); //返回给定日历的值
abstract public void add(int field, int amount); //给给定字段添加或减去指定的时间量
3、Scanner类
Scanner类是java.util包下的一个常用于扫描输出的类,Scanner类被final修饰无法被继承,同时实现了cloneable和Iterator接口。Scanner类的构造器包括键盘输入,字符串,文件,输入流等多种方式。
Scannner的常用方法
Scanner input = new Scannner(System.in);
我们经常需要用到Scanner类读取键盘输入
其中nextInt()、nextDouble()、nextBoolean()、nextShort()、nextByte()等分别用于读取相应类别的数据。
next()与nextLine()都可用于读取字符串,但next()中不可以包括空格,读取后光标仍指向本行
而nextLine()可以读取包含空格的字符串,读取完后光标指向下一行。
(Tips:也可以使用useDelimiter()方法将默认分隔符空格改为回车,则,next()同样可以读取带空格的字符序列)
另外hasNextInt()、hasNextDouble()、hasNextBoolean()、hasNextShort()、hasNextByte()、hasNext()等方法也是很常用的,这些方法主要用于判断当前输入信息序列中的下一个标记是否是对应类型,如果是,则返回true,常用于判断文件流输入是否结束。
4、Math类和Random类
4.1、Math类
Math类中提供了许多静态方法,可直接调用,调用形式如:
Math.数学方法
Math类主要有以下几个常用方法。
4.1.1、随机数方法
random()方法:用于产生一个double型随机数字,范围在[0.0,1.0)之间。
举例:根据用户提供的两个整数参数返回两个参数之间的任意整数
public class Example4_9 {
public static void main(String[] args) {
int small = Integer.parseInt(args[0]);//将输入的字符串转化为整型
int big = Integer.parseInt(args[1]);//将输入的整数字符串转化为中整型
if (small > big) {//保证small存小值,big存大值
int temp = small;
small = big;
big = temp;
}
int r = (int) Math.random() * (big-small) + small;//强制转换的格式:(类型名)表达式
System.out.println(r);//使用快捷键sout
}
}
4.1.2.最大值、最小值、绝对值方法
方法名
max(a,b); //求a、b两者最大
min(a,b); //求a、b两者最小
abs(a); //求a的绝对值
以上3个方法的参数类型可以是多种数值类型
应用
public class Example4_9 {
public static void main(String[] args) {
int small = Integer.parseInt(args[0]);//将输入的字符串转化为整型
int big = Integer.parseInt(args[1]);//将输入的整数字符串转化为中整型
if (small > big) {//保证small存小值,big存大值
int temp = small;
small = big;
big = temp;
}
int r = (int) Math.random() * (big-small) + small;//强制转换的格式:(类型名)表达式
System.out.println(r);
System.out.println(Math.max(small,big));//最大
System.out.println(Math.min(small,big));//最小
System.out.println(Math.abs(small-big));//绝对值
}
}
4.1.3、取整数方法
方法名
double ceil(double a);//返回大于等于参数a的最小整数
double floor(double a);//返回小于等于参数a的最大整数
double rint(double a);//返回与参数a最接近的整数,偶数优先
4.2、Random类
4.2.1、Random类的两种构造方法
定义:Random类在java.util包中,在指定的范围内随机产生数字
构造方法:
Random(long seed); //有参构造,如果传入的数据相同,不同对象可产生相同的随机数
Random(); //无参构造,对于每次对象创建的随机数不同
4.2.2、Random类的常用方法
前面的Math类中的random()方法只产生double型的随机数,而在Radom类中提供多种方法获取不同数据类型的随机数,具体可查看API文档,已多次推荐,非常好用,适合新手。
举个例子说明方法:
public class Example4_11 {
public static void main(String[] args) {
Random r1 = new Random();//使用无参构造对象
System.out.println(r1.nextFloat());//产生0.0~1.0间的float类型的值
System.out.println(r1.nextDouble());//产生0.0~1.0间的double类型的值
System.out.println(r1.nextInt());//产生0.0~1.0间的int类型的值
System.out.println(r1.nextInt(10));//产生[0,10)间的int类型的值
Random r2 = new Random(6);//使用有参构造对象,若参数相同,产生随机数相同
Random r3 = new Random(6);//使用有参构造对象,若参数相同,产生随机数相同
System.out.println(r2.nextInt() == r3.nextInt());
}
}
5、数字格式化
在Java中,所有新的格式化功能都由java.util.Formatter类处理。可以将Formatter看作一个翻译器,他将你的格式化字符串与数据翻译成需要的结果。当你创建一个Formatter对象的时候,需要向其构造器传递一些信息,告诉他最终的结果将向哪里输出:
package com.tij;
//TIJ P290
import java.io.PrintStream;
import java.util.Formatter;
public class Turtle {
private String name;
private Formatter f;
public Turtle(String name,Formatter f){
this.name=name;
this.f=f;
}
public void move(int x, int y) {
f.format("%s The Turtle is at (%d,%d)\n",name,x,y);
}
public static void main(String[] args) {
PrintStream outAlias=System.out;
Turtle tommy = new Turtle("Tommy", new Formatter(System.out));
Turtle terry = new Turtle("Terry", new Formatter(outAlias));
tommy.move(0,0);
terry.move(3,5);
tommy.move(2,5);
terry.move(2,8);
}
}
/*
*output:
Tommy The Turtle is at (0,0)
Terry The Turtle is at (3,5)
Tommy The Turtle is at (2,5)
Terry The Turtle is at (2,8)
*/
所有的tommy都将输出到System.out,而所有的terry输出到System.out的一个别名中。Formatter的构造器经过重载可以接受多种输出目的地,不过最常用的还是PrintStream()、OutputStream和File.
6、StringBuffer类
-
java.lang.StringBuffer 代表可变的字符序列。
-
StringBuffer和String类似,但StringBuffer可以对其字符串进行改变
1.StringBuffer类的常见构造方法
1.StringBuffer() //创建一个不包含字符序列的“空”的StringBuffer对象。 2.StringBuffer(String str) //创建一个StringBuffer对象,包含与String对象str相同的字符序列。
2.StringBuffer类的常用方法
重载方法 public StringBuffer append(…) 可以为该StringBuffer对象添加字符序列,返回添加后的该StringBuffer对象引用,例如
public StringBuffer append(String str) public StringBuffer append(StringBuffer sbuf) public StringBuffer append(char[] str) public StringBuffer append(char[] str,int offset,int len) public StringBuffer append(double d) public StringBuffer append(Objectobj)
重载方法 public StringBuffer insert(…) 可以为该StringBuffer对象在指定位置插入字符序列,返回修改后的该stringBuffer对象引用,例如
public StringBuffer insert(int offset,String str) public StringBuffer insert(int offset,double d)
方法 public StrinaBuffer delete(int start,int end) 可以删除从start开始到end-1为止的一段字符序列,返回修改后的该strinqBuffer对象引用。
String类含义类似 的方法
public int indexOf(string str) public int indexOf(String str,int fromIndex) public string substring(int start) public String substring(int start,int end) public int length()
7、包装类
八种基本数据类型对应的包装类型名
基本数据类型 | 包装类型 |
---|---|
byte | java.lang.Byte(父类Number) |
short | java.lang.Short(父类Number) |
int | java.lang.Integer(父类Number) |
long | java.lang.Long(父类Number) |
float | java.lang.Float(父类Number) |
double | java.lang.Double(父类Number) |
boolean | java.lang.Boolean(父类Object) |
char | java.lang.Character(父类Object |
注意: 8种包装类属于 引用数据类型
包装类的一些特性:
· 所有包装类都可以将与之对应的基本数据类型作为参数来创建它们的实例对象
· 除了Character类之外,其他包装类都可以将一个字符串作为参数来构造它们的实例
· Boolean类的构造方法参数为String类型时,若该字符串为true(不论大小写),则该对象表示true,否则表示false
· 当包装类Number构造方法的参数为String类型时,字符串不能为null,并且该字符串必须能够解析为基本类型的数据
用途
· 集合不允许存放基本数据类型,故常用包装类
· 包含了每种基本数据类型的相关属性,如最大值、最小值、所占位数等
· 作为基本数据类型对应的类型,提供了一系列实用的对象操作,如类型转换、进制转换等方法
常见考点
1、包装类中“==”与equals的用法比较
值得注意的是,包装类中的equals方法和String类一样,都是重写了Object类中的equals方法,因此比较的是内容而不是地址,而“”比较的依然是引用变量的地址,只是当包装类型和与之相对应的基本类型进行“”比较时会先做自动拆箱处理。
2、包装类缓存
部分包装类提供了对象的缓存,实现方式是在类初始化时提前创建好会频繁使用的包装类对象,当需要使用某个包装类的对象时,如果该对象包装的值在缓存的范围内,就返回缓存的对象,否则就创建新的对象并返回。