基本概念
StringBuffer和StringBuilder类
➢在Java之中,字符串使用String类来进行表示,但是String类所表示的字符串有一个最大的问题:“字符串常量一 但声明则不可改变, 而字符串对象可以改变,但是改变的是其内存地址的指向”。所以String类不适合于被频繁修改的字符串操作上,所以在这种情况下,往往可以使用StringBuffer类,即: StringBuffer类方便用户进行内容的修改。在String类之 中使用"+”作为数据库的连接操作,而在StringBuffer类之 中使用append()方法(方法定义: public StringBuffer append(数据类型变量))进行数据的连接。
StringBuffer基本使用
public class Main {
public static void main(String args[]) throws Exception {
//String类可以直接赋值实例化,但StringBuffer不行需要new
StringBuffer buffer = new StringBuffer();
buffer.append("你").append("好");
change(buffer);
System.out.println(buffer);
}
//入参为引用类型时,传递的是地址的拷贝(即:buffer的地址)
public static void change(StringBuffer stringBuffer){
stringBuffer.append("666");
}
}
结果:你好666
String和StringBuffer
String与StringBuffer两个类都是进行字符串操作的,为了进一步理解这两个类的关系,下面来介绍这两个类的定义结构。
String类: | StringBuffer类: |
---|---|
public final class String extends object implements Serializable, Comparable,CharSequence | public final class StringBuffer extends object implements Serializable, CharSequence |
通过两个类的结构可以发现,String类与StringBuffer类都是 CharSequence接口的子类,也就说明String或StringBuffer类的对象都可以利用自动向上转型的操作为CharSequence接口实例化。
取得CharSequence接口实例化对象
public class Main {
public static void main(String args[]) {
CharSequence seq = "aaa"; //String类实例化对象向上转型为CharSequence接口对象
System.out.println(seq); //String类覆写的toString()
}
}
结果:aaa
虽然String和StringBuffer都属于CharSequence接口的子类,但是这两个类对象是不能直接转换的。
将String转换为StringBuffer类对象
方式一:利用StringBuffer类的构造方法(public StringBuffer(String str))
public class Main {
public static void main(String args[]) {
StringBuffer stringBuffer = new StringBuffer("aaa");
System.out.println(stringBuffer);
}
}
结果:aaa
方式二:利用StringBuffer类中的append()方法(public synchronized StringBuffer append(String str))
public class Main {
public static void main(String args[]) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("aac");
System.out.println(stringBuffer);
}
}
结果:aac
将StringBuffer转换为String类对象
方式一:利用toString()方法可以将StringBuffer转化为String。
public class Main {
public static void main(String args[]) {
StringBuffer stringBuffer = new StringBuffer("aaa");
String str = stringBuffer.toString();
System.out.println(str);
}
}
结果:aaa
实际上所有的类都会继承Object类的toString()方法,所以所有类对象都可以转换为String类对象。
方式二:利用String类的构造方法(public String(StringBuffer buffer))
public class Main {
public static void main(String args[]) {
StringBuffer stringBuffer = new StringBuffer("aaa");
String str = new String(stringBuffer);
System.out.println(str);
}
}
结果:aaa
String对象与StringBuffer对象比较
由于String与StringBuffer都表示字符串,所以在String类里面也提供了一个和StringBuffer比较的方法:public boolean contentEquals(StringBuffer sb),注意需要区分大小写。
public class Main {
public static void main(String args[]) {
StringBuffer stringBuffer = new StringBuffer("aaa");
System.out.println("aaa".contentEquals(stringBuffer));
}
}
结果:true
StringBuffer类常用操作
NO. | 方法 | 类型 | 描述 |
---|---|---|---|
1 | public StringBuffer append(数据类型 变量) | 普通 | 数据追加操作 |
2 | pubilc StringBuffer reverse() | 普通 | 字符串反转操作 |
3 | public StringBuffer insert(int offset,数据类型 变量) | 普通 | 在指定位置追加数据 |
4 | public StringBuffer delete(int start,int end) | 普通 | 删除指定范围内的数据 |
字符串反转
public class Main {
public static void main(String args[]) throws Exception {
StringBuffer buffer = new StringBuffer("abc");
System.out.println(buffer.reverse());
}
}
结果:cba
在指定索引位置添加数据
public class Main {
public static void main(String args[]) throws Exception {
StringBuffer buffer = new StringBuffer("abc");
buffer.insert(1,"哈哈");
System.out.println(buffer);
}
}
结果:a哈哈bc
删除指定索引位置数据
public class Main {
public static void main(String args[]) throws Exception {
StringBuffer buffer = new StringBuffer("abc1234");
//不包括末位置的数据
buffer.delete(1,3);
System.out.println(buffer);
}
}
结果:a1234
StringBuilder类的不同之处
从JDK1.5开始,JAVA增加了一个新的字符串操作类:StringBuilder。结构定义如下:
public final class StringBuilder
extends Object
implements Serializable, CharSequence
区别如下:在StringBuffer类中定义的方法全部使用了“synchronized”进行同步定义,而StringBuilder类没有进行同步定义,都是异步方法,属于非线城安全的操作。
Runtime类
➢在每一个JVM进程之中, 都会存在一个运行时的操作类的对象, 而这对象所属的类型就是Runtime类。利用Runtime类可以启动新的进程或者是进行相关运行时环境的操作,例如:取得内存空间以及垃圾空间释放。
NO. | 方法 | 类型 | 描述 |
---|---|---|---|
1 | public static Runtime getRuntime() | 普通 | 取得Runtime类实例化对象 |
2 | pubilc long maxMemory() | 普通 | 返回最大可用内存大小,返回字节 |
3 | public long totalMemory() | 普通 | 返回所有可用内存大小,返回字节 |
4 | public long freeMemory() | 普通 | 返回所有空余内存大小,返回字节 |
5 | public void gc() | 普通 | 执行垃圾回收操作 |
6 | public Process exec(String command) throws IOException | 普通 | 创建新的进程 |
观察内存大小
public class Main {
public static void main(String args[]) throws Exception {
Runtime runtime = Runtime.getRuntime();
System.out.println("MAX=" + runtime.maxMemory());
System.out.println("TOTAL=" + runtime.totalMemory());
System.out.println("FREE=" + runtime.freeMemory());
}
}
结果:MAX=1866465280
TOTAL=126877696
FREE=123506504
观察gc()使用前后内存变化
public class Main {
public static void main(String args[]) throws Exception {
Runtime runtime = Runtime.getRuntime();
String str = "";
System.out.println("MAX=" + runtime.maxMemory());
System.out.println("TOTAL=" + runtime.totalMemory());
System.out.println("FREE=" + runtime.freeMemory());
for(int i = 0; i < 2000; i++){
str += i;
}
runtime.gc();
System.out.println("后MAX=" + runtime.maxMemory());
System.out.println("后TOTAL=" + runtime.totalMemory());
System.out.println("后FREE=" + runtime.freeMemory());
}
}
结果:MAX=1866465280
TOTAL=126877696
FREE=123506504
后MAX=1866465280
后TOTAL=126877696
后FREE=124883792 //清除之后比之前空余内存都高了
Runtime类还有一个更有意思的功能,就是可以调用本机的可执行程序,并且创建进程。
创建一个进程
public class Main {
public static void main(String args[]) throws Exception {
Runtime runtime = Runtime.getRuntime();
Process exec = runtime.exec("mspaint.exe");
//进程暂停2s
Thread.sleep(2000);
//进程销毁
exec.destroy();
}
}
System类
NO. | 方法 | 类型 | 描述 |
---|---|---|---|
1 | pubilc static long currentTimeMillis()() | 普通 | 取得当前时间,返回毫秒 |
2 | public static void gc() | 普通 | 垃圾收集 |
计算某次操作所花费时间
public class Main {
public static void main(String args[]) throws Exception {
long start = System.currentTimeMillis();
int x = 0;
//循环次数要足够大,不然比较难看出
for(int i = 0; i < 20000000; i++){
x += i;
}
long end = System.currentTimeMillis();
System.out.println("所花费时间:"+ (end - start));
}
}
结果:所花费时间:8
对象回收操作
暂无
克隆
克隆就是对象的复制操作,在Object类中存在clone()方法:
➢克隆方法: protected Object clone() throws CloneNotSupportedException;
➢此方法是实现克隆的唯一方法, 所有类的对象只有调用此方法才可以进行克隆,但是此方法本身使用了protected访问权限,这样当在不同的包产生对象时将无法调用Object类中的clone0方法,为此就需要子类来覆写clone()方法(但依然调用的是父类中的clone()方法) ,可以正常完成克隆操作
标识性接口
在clone()方法上抛出一个”CloneNotSupportedException“(不支持的克隆异常)。这是因为不是所有类的对象都可以被克隆。在JAVA中为了区分哪些类对象可以被克隆,专门提供了一个Cloneable接口,也就是说要被克隆对象的类必须失效该接口。
但是Cloneable接口没有任何方法,所以这个接口属于标识接口,用于表示一种能力。
实现克隆操作
package com.company;
class Book implements Cloneable{ //此类对象可以被克隆
private String title;
private double price;
public Book(String title, double price) {
this.title = title;
this.price = price;
}
public void setTitle(String title){
this.title = title;
}
@Override
public String toString() {
return "Book{" +
"title='" + title + '\'' +
", price=" + price +
'}';
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Main {
public static void main(String args[]) throws Exception {
Book bookA = new Book("电视", 78.89);
Book bookB = (Book) bookA.clone();
System.out.println(bookA);
System.out.println(bookB);
}
}
结果:Book{title='电视', price=78.89}
Book{title='电视', price=78.89}
数字操作类
Math类
➢Math就是一个专门进行数学计算的操作类,里面提供了一系列的数学计算方法 (例如:对数、绝对值、幂运算等)。在Math类里面提供的一切方法都是static型的方法,所以可以直接由类名称进行调用。在整个Math类中有一个方法需 要为读者特别说明,那就是四舍五入的操作方法(public static long round(double a))。
观察四舍五入
public class Main {
public static void main(String args[]) throws Exception {
System.out.println(Math.round(15.5));
System.out.println(Math.round(-15.5));
System.out.println(Math.round(-15.51));
}
}
结果:16
-15
-16
上述程序完成了一个基本的四舍五入操作,需要注意的是当为负数时的情况。
Random类
➢java.util.Random是一个专门 负责产生随机数的操作类
NO. | 方法 | 类型 | 描述 |
---|---|---|---|
1 | pubilc Random() | 构造 | 创建一个新的Random实例对象 |
2 | public Random(long seed) | 构造 | 创建一个新的Random实例对象并设置一个种子数 |
3 | public int nextInt(int bound) | 普通 | 产生一个不大于指定边界的随机整数(≥0) |
基本使用
public class Main {
public static void main(String args[]) throws Exception {
Random random = new Random();
for(int i = 0; i < 10; i++){
//随机生成 0 ~99 的整数(包括0和99)
System.out.println(random.nextInt(100));
}
}
}
编写36选7的彩票程序
import java.util.Arrays;
import java.util.Random;
public class Main {
public static void main(String args[]) {
Random random = new Random();
int[] data = new int[7];
int foot = 0;
while (foot < 7){ //不确定循环次数用while
int t = random.nextInt(37);
if(isRepeat(data,t)){
data[foot++] = t; //或者这里写foot,然后用下面一行的代码
//foot++;
}
}
Arrays.sort(data); //排序一下
for(int i : data){
System.out.print(i+"、");
}
}
public static boolean isRepeat(int[] item,int num){
if(num == 0){
return false;
}
for(int i : item){
if(i == num){
return false;
}
}
return true;
}
}
大数字操作类
➢如果说现在有两个非常大的数字要进行数学操作(这个时候数字已经超过了double的范围), 那么则只能利用字符串来表示,取出每一位字符变为数字后进行数学计算, 但是这种方式的难度较高,为了解决这样的问题,在Java里面提供了两个大数字操作类: java.math.BigInteger、java.math.BigDecimal, 而这两个类是属于Number的子类。
超过数据范围的计算
public class Main {
public static void main(String args[]) {
System.out.println(Double.MAX_VALUE*Double.MAX_VALUE);
}
}
结果:Infinity
Infinity表示一个无穷的数据,也是一种错误表示。如果是数据很大的数字要进行计算,只能将其变为String类型,然后按位取出每一个字符保存的数据,进行手工计算。
大整数操作类:BigInteger
BigInteger类操作方法
NO. | 方法 | 类型 | 描述 |
---|---|---|---|
1 | pubilc BigInteger(String val) | 构造 | 创建一个新的BigInteger实例对象 |
2 | public BigInteger add(BigInteger val) | 普通 | 加法操作 |
3 | public BigInteger subtract(BigInteger val) | 普通 | 减法操作 |
4 | public BigInteger multiply(BigInteger val) | 普通 | 乘法操作 |
5 | public BigInteger divide(BigInteger val) | 普通 | 除法操作(不保留余数) |
6 | public BigInteger[] divideAndRemainder(BigInteger val) | 普通 | 除法操作(保留余数),数组一个是商,第二个是余数 |
基本操作
public class Main {
public static void main(String args[]) throws Exception {
BigInteger integerA = new BigInteger("121764387893064");
BigInteger integerB = new BigInteger("8749837638876");
System.out.println("加法操作:" + integerA.add(integerB));
System.out.println("减法操作:" + integerA.subtract(integerB));
System.out.println("乘法操作:"+integerA.multiply(integerB));
System.out.println("除法操作:"+integerA.divide(integerB));
BigInteger[] bigIntegers = integerA.divideAndRemainder(integerB);
System.out.println("除法操作:商" + bigIntegers[0] + "余数:" + bigIntegers[1]);
}
}
结果:加法操作:130514225531940
减法操作:113014550254188
乘法操作:1065418624261428510137156064
除法操作:13
除法操作:商13余数:8016498587676
大小数操作类:BigDecimal
BigDecimal类表示大小书操作类,但是这个类也具备与BigInteger类同样的基本计算方法。
BigDecimal类操作方法
NO. | 方法 | 类型 | 描述 |
---|---|---|---|
1 | pubilc static final int ROUND_HALF_UP | 常量 | 向上进一位(也就是常说的四舍五入模式) |
2 | public BigDecimal(double val) | 构造 | 传递一个double型数据 |
3 | public BigDecimal divide(BigDecimal b,int s,int mode ) | 普通 | 除法操作:1. b 被除数。2.s 保留小数位长度。 3. mode 进位模式 |
完成四舍五入操作
public class Main {
public static void main(String args[]) {
BigDecimal bigDecimal = new BigDecimal(15.5551);
BigDecimal divide = bigDecimal.divide(new BigDecimal(1), 2, BigDecimal.ROUND_HALF_UP);
System.out.println(divide);
}
}
结果:15.56
日期处理类
Date类
➢在之前一直在强调简单Java类的概念, 也重点阐述了简单Java类和数据表之间的映射关系的,但是对于数据表的日期型字段却一直没有映射,而在Java之中,如果要想表示出日期型,则使用java.util.Date类完成。
NO. | 方法 | 类型 | 描述 |
---|---|---|---|
1 | pubilc Date() | 构造 | 实例化Date对象 |
2 | public Date(long date) | 构造 | 将数字变为Date类对象,long为日期时间数据 |
3 | public long getTime() | 普通 | 将当前日期变为long型 |
取得当前日期
public class Main {
public static void main(String args[]) throws Exception {
Date date = new Date();
System.out.println(date);
}
}
结果:Thu Jun 11 17:00:12 CST 2020
Date与long间的转换
public class Main {
public static void main(String args[]) throws Exception {
long cur = System.currentTimeMillis();
//long转换为Date
Date date = new Date(cur);
System.out.println(date);
//Date转换为long
System.out.println(date.getTime());
}
}
日期格式化:SimpleDateFormat
➢虽然使用java.util.Date类可以明确的取得当前的日期时间,但是最终数据的显示格式并不方便阅读。如果要对显示的日期时间进行格式转换,则可以通过java.text. SimpleDateFormat类完成
NO. | 方法 | 类型 | 描述 |
---|---|---|---|
1 | pubilc SimpleDateFormat(String str) | 构造 | 传入日期时间格式标记实例化对象 |
2 | public final String format(Date date) | 普通 | 将日期格式化为字符串数据 |
3 | public Date parse(String source) throws ParseException | 普通 | 将字符串格式化为日期数据 |
将日期格式化显示
public class Main {
public static void main(String args[]) throws Exception {
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String format = dateFormat.format(date);
System.out.println(format);
}
}
结果:2020-06-11 17:22:40.968
将字符串转化为日期
public class Main {
public static void main(String args[]) throws Exception {
String s = "2019-12-20 12:25:32.234";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date parse = dateFormat.parse(s);
System.out.println(parse);
}
}
结果:Fri Dec 20 12:25:32 CST 2019
Calendar类
➢Calendar类可以将取得的时间精确到毫秒,并且由于其可以分别取得日期时间数字,这样可以直接进行各种日期时间的计算操作
NO. | 常量及方法 | 类型 | 描述 |
---|---|---|---|
1 | pubilc static final int YEAR | 常量 | 取得年,int类型 |
2 | pubilc static final int MONTH | 常量 | 取得月,int类型 |
3 | pubilc static final int DAY_OF_MONTH | 常量 | 取得日,当月中的第几日,int类型 |
4 | pubilc static final int HOUR_OF_DAY | 常量 | 取得小时,24小时制,int类型 |
5 | pubilc static final int MINUTE | 常量 | 取得分,int类型 |
6 | pubilc static final int SECOND | 常量 | 取得秒,int类型 |
7 | pubilc static final int MILLISECOND | 常量 | 取得毫秒,int类型 |
8 | pubilc static Calendar getInstance() | 普通 | 根据默认时区实例化对象 |
9 | public boolean after(Object when) | 普通 | 判断一个日期是否在指定日期之后 |
10 | public boolean before(Object when) | 普通 | 判断一个日期是否在指定日期之前 |
11 | public int get(int field) throws ParseException | 普通 | 返回给定日历字段的值 |
取得当前日期时间
public class Main {
public static void main(String args[]) throws Exception {
Calendar calendar = Calendar.getInstance();
StringBuffer buffer = new StringBuffer();
buffer.append(calendar.get(Calendar.YEAR)).append("-");
//需要注意月份从0开始
buffer.append(calendar.get(Calendar.MONTH)+1).append("-");
buffer.append(calendar.get(Calendar.DAY_OF_MONTH)).append(" ");
buffer.append(calendar.get(Calendar.HOUR_OF_DAY)).append(":");
buffer.append(calendar.get(Calendar.MINUTE)).append(":");
buffer.append(calendar.get(Calendar.SECOND)).append(".");
buffer.append(calendar.get(Calendar.MILLISECOND));
System.out.println(buffer);
}
}
结果:2020-5-11 18:4:35.655
比较器
暂无
需要比较数组和集合