稳稳当当学java之工具类(14)

第十六章 工具类

1.作业回顾

//1,创建一个类Student,属性int id,String name,char gender,int age,
//重写toString方法,重写hashCode和equals方法。
class Student {
	private int id;
	private String name;
	private char gender;
	private int age;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public char getGender() {
		return gender;
	}
	public void setGender(char gender) {
		this.gender = gender;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}

	public Student(int id, String name, char gender, int age) {
			super();
			this.id = id;
			this.name = name;
			this.gender = gender;
			this.age = age;
	}
	
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", gender=" + gender + ", age=" + age + "]";
	}

	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + gender;
		result = prime * result + id;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (age != other.age)
			return false;
		if (gender != other.gender)
			return false;
		if (id != other.id)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
}
//创建两个对象,使用equals方法比较两个对象是否相等。
public class Day1514 {
	public static void main(String[] args) {
		Student s1 = new Student(20191101, "张三", '男', 20);
		Student s2 = new Student(20191102, "李四", '女', 21);
		
		System.out.println(s1.equals(s2));//false
		
		System.out.println(s1);//Student [id=20191101, name=张三, gender=男, age=20]
		System.out.println(s2);//Student [id=20191102, name=李四, gender=女, age=21]
	}
}
//2,将二进制数1001000111110101,转换为十六进制数和八进制数并输出。
public class Day1515 {
	public static void main(String[] args) {
		int i = Integer.parseInt("1001000111110101", 2);
		System.out.println(Integer.toString(i, 8));//110765
		System.out.println(Integer.toString(i, 16));//91f5		
		
		System.out.println(Integer.toOctalString(i));//八进制//110765
		System.out.println(Integer.toHexString(i));//十六进制//91f5

	}
}

2. String类

String类可以存储字符序列,它不是基本数据类型,而是引用类型。

2.1 创建字符串对象的两种方式

1.使用字面值创建 2.使用构造器创建

public class Day1603 {
	public static void main(String[] args) {
		//str1引用了一个字符串
		String str1 = "hello";//使用字面值创建一个字符串对象
		
		String str2 = new String("hello");//使用构造器创建一个字符串对象
	}
}

2.2 String类内部使用字符数组来保存字符串。

import java.util.Arrays;

public class Day1604 {
	public static void main(String[] args) {
		char[] chars = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
		//通过字符数组构造出一个字符串对象
		String str = new String(chars);
		
		System.out.println(str);//abcdefg
		
		char[] arr = str.toCharArray();
		System.out.println(Arrays.toString(arr));//[a, b, c, d, e, f, g]
	}
}

2.3 字符串对象是不可变的

如果一个对象没有实例方法可以修改自身的属性,那么这个对象就是不可变的。

对字符串对象的任何修改都将创建一个新的对象,而原来的字符串对象保存不变。

public class Day1605 {
	public static void main(String[] args) {
		//str1是对象变量
		String str1 = "value1";
		//concat方法将参数参数字符串连接到str1的末尾
		String str2 = str1.concat(str1);
		System.out.println(str1);//value1, 不改变原字符串对象
		System.out.println(str2);//value1value2
		
		String str3 = "value3";
		System.out.println(str3);//value3
	}
}
public class Day1606 {
	public static void main(String[] args) {
		//避免重复创建对象,字符串常量池相当于一个缓存
		//创建一个字符串对象,放入字符串常量池,并将其地址赋值给str1
		String str1 = "value";
		//从字符串常量池中获取字符串对象,并将地址赋值给str2
		String str2 = "value";
		System.out.println(str1 == str2);//true
	}
}
public class Day1608 {
	public static void main(String[] args) {
		String str1 = new String("abc");
		String str2 = new String("abc");
		System.out.println(str1 == str2);//false
		//String类重写了Object类的equals方法,比较的是字符串对象的内容
		System.out.println(str1.equals(str2));//true
	}
}

2.4 String类的常用方法

2.4.1获取字符串的信息
public class Day1609 {
	public static void main(String[] args) {
		//char chatAt(int paramInt),获取指定索引处的字符
		System.out.println("abcdefg".charAt(2));//c
		
		//boolean contains(CharSequence s),测试此字符串是否包含指定的字符序列
		//(CharSequence s)这里的CharSequence理解为一个接口变量可以引用实现该接口的类的实例
		System.out.println("abcdefg".contains("cde"));//true
		System.out.println("abcdefg".contains("abcdefg"));//true
		
		//int length(),返回此字符串的长度。
		System.out.println("abcdefg".length());//7
		
		//boolean startsWith(String prefix),测试此字符串是否以指定的前缀开始。
		System.out.println("abcdefg".startsWith("abc"));//true
		
		//boolean endsWith(String suffix),测试此字符串是否以指定的后缀结束。
		System.out.println("abcdefg".endsWith("efg"));//true
		
		//int indexOf(int ch),返回指定字符在此字符串中第一次出现处的索引。
		//(int ch)这里的int理解为字符"c"在计算机中用整数表示
		System.out.println("abcdefg".indexOf("c"));//2
		
		//int indexOf(int ch, int fromIndex),返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索。
		System.out.println("abcdefg".indexOf("c", 0));//2
		System.out.println("abcdefg".indexOf("c", 3));//-1
		
		//int indexOf(String str),返回指定子字符串在此字符串中第一次出现处的索引。
		System.out.println("abcdefg".indexOf("cde"));//2
		System.out.println("abcdefg".indexOf("ce"));//-1
		System.out.println("abcdefg".indexOf("abcdefg"));//0
		
		//int indexOf(String str, int fromIndex),返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。
		System.out.println("abcdefg".indexOf("cde", 0));//2
		System.out.println("abcdefg".indexOf("cde", 2));//2
		System.out.println("abcdefg".indexOf("cde", 3));//-1
		System.out.println("abcdefg".indexOf("cde", 5));//-1
		
		//int lastIndexOf(int ch),返回指定字符在此字符串中最后一次出现处的索引。
		System.out.println("abcdefa".lastIndexOf("a"));//6
		
		//int lastIndexOf(int ch, int fromIndex),返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索。
		System.out.println("abcdefa".lastIndexOf("a", 6));//6
		System.out.println("abcdefa".lastIndexOf("a", 3));//0
		
		//int lastIndexOf(String str),返回指定子字符串在此字符串中最后一次出现处的索引。
		System.out.println("abcdefa".lastIndexOf("a"));//6
		
		//int lastIndexOf(String str, int fromIndex),返回指定子字符串在此字符串中最后一次 出现处的索引,从指定的索引处开始进行反向搜索。
		System.out.println("abcdefa".lastIndexOf("a", 6));//6
		System.out.println("abcdefa".lastIndexOf("a", 3));//0
		
		//boolean equalsIgnoreCase(String anotherString) 
		//将此 字符串 与另一个 字符串 比较,不考虑大小写。
		System.out.println("abcdefg".equalsIgnoreCase("ABCDEFG"));//true	
	}
}
2.4.2字符串操作方法

字符串对象是不可变的,对字符串对象的任何修改都将创建一个新的对象,而原来的字符串对象保存不变。

public class Day1610 {
	public static void main(String[] args) {
		String str = "abcdefg";
		//String concat(String paramString),将指定字符串连接到此字符串的结尾。
		System.out.println(str.concat("lmn"));//abcdefglmn
		System.out.println(str);//abcdefg
		
		//String replace(char oldChar, char newChar) 
		//返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。
		System.out.println("1010".replace("0", "1"));//1111
		
		//String replace(CharSequence target, CharSequence replacement) 
		//返回一个新的字符串,它是通过用 replacement 替换此字符串中出现的所有 target 得到的。
		System.out.println("yourcar".replace("your", "my"));
		
		//String toLowerCase() 
		//将此 String中的所有字符都转换为小写。
		System.out.println("ABCDEFG".toLowerCase());//abcdefg
		
		//String toUpperCase() 
		//将此 String 中的所有字符都转换为大写。
		System.out.println("abcdefg".toUpperCase());//ABCDEFG
		
		//String trim() 
		//返回字符串的副本,忽略前导空白和尾部空白。
		System.out.println("  ab  cde  fg  ".trim());//ab  cde  fg
		
		//String substring(int beginIndex),获取从指定索引处开始的子字符串
		System.out.println("abcdefg".substring(3));//defg
		
		//String substring(int beginIndex,int endIndex)
		//获取beginIndex和endIndex之间的子字符串,包含开始字符,不包含结束字符。
		System.out.println("abcdefg".substring(3, 6));//def	
	}
}
2.4.3字符串连接

规则1:数值+数值=数值

规则2:数值+字符串=字符串

规则3:除非有括号,否则表达式的求值顺序是从左到右

public class Day1611 {
	public static void main(String[] args) {
		System.out.println(5 + "Test" + 5);//5Test5
		System.out.println(5 + 5 + "Test");//10Test
		System.out.println("5" + 5 + "Test");//55Test
		System.out.println("5" + "5" + "25");//5525
		System.out.println("" + 5 + 5 + "25");//5525
		System.out.println(5 + (5 + "25"));//5525
		System.out.println(5 + 5 + "25");//1025
		System.out.println(5 + 5 + 25);//35
	}
}

3.StringBuilder和StringBuffffer

频繁的使用+操作符进行字符串拼接会创建大量的字符串对象,更加优雅的做法是使用StringBuilder和StringBuffffer。

StringBuilder不是线程安全的,但是执行效率高。

StringBuffffer是线程安全的,但是执行效率低。

public class Day1612 {
	public static void main(String[] args) {
		StringBuilder s1 = new StringBuilder();
		//将世追加到StringBuilder对象的末尾
		s1.append("世");
		//将界追加到StringBuilder对象的末尾
		s1.append("界");
		//将和追加到StringBuilder对象的末尾
		s1.append("和");
		//将平追加到StringBuilder对象的末尾
		s1.append("平");
		
		//将内容以字符串对象返回
		String str = s1.toString();
		System.out.println(str);//世界和平
		
		//append方法将参数拼接到内部的字符数组中并返回this(s1),因此可以进行后续拼接
		s1.append("世").append("界").append("和").append("平");
		System.out.println(s1);//世界和平世界和平	
	}
}

StringBuffffer的方法和StringBuilder的方法一样。

public class Day1612 {
	public static void main(String[] args) {
		StringBuffer s1 = new StringBuffer();
		//将世追加到StringBuffer对象的末尾
		s1.append("世");
		//将界追加到StringBuffer对象的末尾
		s1.append("界");
		//将和追加到StringBuffer对象的末尾
		s1.append("和");
		//将平追加到StringBuffer对象的末尾
		s1.append("平");
		
		//将内容以字符串对象返回
		String str = s1.toString();
		System.out.println(str);//世界和平
		
		//append方法将参数拼接到内部的字符数组中并返回this(s1),因此可以进行后续拼接
		s1.append("世").append("界").append("和").append("平");
		System.out.println(s1);//世界和平世界和平	
	}
}

4.Math数学类

public class Day1613 {
	public static void main(String[] args) {
		System.out.println(Math.sqrt(2.25));//平方根 1.5 
		System.out.println(Math.abs(-2));//绝对值 2 
		System.out.println(Math.pow(3, 3));//幂值 27.0 
		System.out.println(Math.max(3, 4));//最大值4 
		System.out.println(Math.min(3, 4));//最小值3 
		System.out.println(Math.random());//大于等于0,小于1的double类型的数 
		System.out.println(Math.round(14.5));//四舍五入 15 

		//5-10之间的随机数
		int i = (int) (Math.random() * 5) + 5; 
		System.out.println(i);			
	}
}

5.Date日期类

java.util.Date类现在已经不推荐使用了,此类的很多方法都被标注为已过时。

Date类对象存储从1970年1月1日0时0分0秒到创建时的毫秒数。

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Day1614 {
	public static void main(String[] args) throws ParseException {
		Date date = new Date();
		//返回距1970年1月1日0时0分0秒的毫秒数
		System.out.println(date.getTime());//1598002011702
		System.out.println(date);//Fri Aug 21 17:26:51 CST 2020
		
		//对于日期的所有操作都需要将时间转换为毫秒数来进行修改。 
		//增加6个小时
		date.setTime(date.getTime() + 6 * 60 * 60 * 1000);
		System.out.println(date);//Fri Aug 21 23:28:22 CST 2020
		
		//对于日期的所有操作都需要将时间转换为毫秒数来进行修改。 
		//减少6个小时
		date.setTime(date.getTime() - 6 * 60 * 60 * 1000);
		System.out.println(date);//Fri Aug 21 17:29:23 CST 2020
		
		//可以使用SimpleDateFormat对日期进行格式化。
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss");
		String str = sdf.format(date);
		System.out.println(str);//2020-08-21:17:40:09
		
		//将一个字符串解析成一个日期对象
		Date d = sdf.parse("2020-08-21:17:40:09");
		System.out.println(d);//Fri Aug 21 17:40:09 CST 2020
	}
}

6.Calendar类

Calendar类可以对日期进行操作:增加和减少(年,月,日,时,分,秒)

Calendar类是一个抽象类,不能直接创建实例。可以使用静态方法getInstance获得Calendar类的一个实例。

import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Day1615 { 
	public static void main(String[] args) { 
		//获取一个Calendar实例 
		Calendar cal = Calendar.getInstance(); 
		System.out.println(cal); 
		
		//将日期修改为24 
		cal.set(Calendar.DATE, 24); 
		//修改月份为9月 
		cal.set(Calendar.MONTH, 8);//8 - September 
		//修改年为2010 
		cal.set(Calendar.YEAR, 2010);
		
		System.out.println(cal.get(Calendar.YEAR));//2010 
		System.out.println(cal.get(Calendar.MONTH));//8 
		System.out.println(cal.get(Calendar.DATE));//24 
		System.out.println(cal.get(Calendar.WEEK_OF_MONTH));//4 
		System.out.println(cal.get(Calendar.WEEK_OF_YEAR));//39 
		System.out.println(cal.get(Calendar.DAY_OF_YEAR));//267 
		System.out.println(cal.getFirstDayOfWeek());//1 -> Calendar.SUNDAY 
		
		//增加5日 
		cal.add(Calendar.DATE, 5);
		System.out.println(cal.getTime());//Wed Sep 29 2010 
		//增加1月 
		cal.add(Calendar.MONTH, 1); 
		System.out.println(cal.getTime());//Fri Oct 29 2010 
		//增加2年 cal.add(Calendar.YEAR, 2); 
		System.out.println(cal.getTime());//Mon Oct 29 2012
		
		//将Calendar对象中的时间点转换为一个Date对象返回 
		Date date = cal.getTime(); 
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss"); 
		String str = sdf.format(date); 
		System.out.println(str); 
	} 
}

7.DecimalFormat

DecimalFormat df1 = new DecimalFormat(".##"); System.out.println(df1.format(1.12556)); 
DecimalFormat df2 = new DecimalFormat(".##%"); System.out.println(df2.format(0.12556));

8.System类

int[] arr1 = {1,2,3,4,5}; 
int[] arr2 = new int[3]; 
System.arraycopy(arr1, 1, arr2, 0, 3);//数组拷贝
System.out.println(Arrays.toString(arr2));//[2,3,4]
System.out.println(System.currentTimeMillis());//返回当前时间距1970年1月1日的毫秒数 
System.out.println(System.getenv("path"));//获取环境变量的值 
System.out.println(System.getProperty("java.version"));//获取系统属性 
System.out.println(System.err);//标准错误输出流 
System.out.println(System.in);//标准输入流 
System.out.println(System.out);//标准输出流

9.Runtime类

Runtime runtime = Runtime.getRuntime(); System.out.println(runtime.freeMemory());//java虚拟机空闲内存数 System.out.println(runtime.maxMemory());//java虚拟机最大内存数

10.练习

1,写一个方法判断字符串是否对称。对称的字符串。abcdefgfedcba

2,写一个方法将字符串中的大写字符转换为小写字符,小写字符转换为大写字符。 String toLowerCase(String str)。abcdeFGH—>ABCDEfgh

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

十年之伴

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

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

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

打赏作者

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

抵扣说明:

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

余额充值