4、常用类和对象
文章目录
- 4、常用类和对象
- 4.1 Object
- 4.2 数组
- 4.3 二维数组
- 4.4 二维数组 九层妖塔
- 4.5 冒泡排序
- 4.6 选择排序
- 4.7 二分法查找
- 4.8 字符串
- 4.9 字符串拼接
- 4.10 字符串比较
- 4.11 字符串截断
- 4.12 字符串替换
- 4.13 字符串大小写转换
- 4.14 字符串查询
- 4.15 StringBuilder
- 4.16 包装类
- 4.17 日期类Date
- 4.18 日历类Calendar
- 4.19 打印日历
- 4.20 工具类
- 4.21 比较(等于)
Java零基础极速入门-讲师:海波
失败,是正因你在距成功一步之遥的时候停住了脚步。
4、常用类和对象
4.1 Object
public class Demo {
public static void main(String[] args) {
// java.lang.Object : 对象
// java所有的类都直接或间接继承Object类
// Object是超类
Object obj = new User();// User间接继承Object,根据多态,这样写正确
// 这样写了之后就只能使用Object中的方法:
// Object中的方法介绍
// 将对象转换成字符串:默认打印对象的内存地址,为了更直观的理解对象的内容,可以重写toString方法
String s = obj.toString(); // 内存地址(十六进制)
// 获取对象的内存地址(十进制)
int i = obj.hashCode();
// 判断两个对象是否相等
// 默认比较内存地址,可以重写
boolean equals = obj.equals(new Person());
// getClass获取对象的类型信息
Class<?> aClass = obj.getClass();
System.out.println(aClass.getSimpleName());
System.out.println(aClass.getPackageName());
// 以上这些方法,在每一个对象中都可以直接使用
}
}
class Person{
// 直接继承Object类
}
class User extends Person{
// 间接继承Object类
}
4.2 数组
public class Demo {
public static void main(String[] args) {
// 数组的声明方式: 类型[] 变量;
// 数组的创建: new 类型[容量];
String[] names = new String[3];
// 给数组的小格子添加数据,添加的方式:数组变量[索引] = 数据;
// 添加数据访问数据时,索引是不能超过指定的范围( 0 ~ length - 1)
// 如果重复给相同的索引添加数据,相当于修改
names[0] = "zhangsan";
names[1] = "lisi";
names[2] = "wangwu";
// 查询(访问)数据,访问的方式:数组变量[索引]
System.out.println(names[0]);
System.out.println(names[1]);
System.out.println(names[2]);
// 使用循环取值,当前数组容量:数组变量.length
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
}
}
4.3 二维数组
数组的存储
二维数组的存储
带行列的二维数组
public class Demo {
public static void main(String[] args) {
// 数组:在创建按数组的同时,添加数据
String[] names = {"zhangsan", "lisi", "wangwu"};
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
// 二维数组
int[][] num = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
// 标准的二维数组
String[][] name = new String[3][3];
// 赋值
name[0][0] = "zhangsan";
System.out.println(name[0][0]);
// 便利所有数据
for (int row = 0; row < name.length; row++) {
for (int col = 0; col < name.length; col++) {
System.out.print(name[row][col]);
}
System.out.println("");
}
}
}
4.4 二维数组 九层妖塔
*
***
*****
*******
*********
***********
*************
***************
*****************
public class Demo {
public static void main(String[] args) {
// 行
int row = 9;
// 列
int col = 2 * row - 1;
// 二维数组[9][17]
String[][] nineTower = new String[row][col];
// 赋值
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (j >= (row - 1) - i && j <= (row - 1) + i) {
nineTower[i][j] = "*";
} else {
nineTower[i][j] = " ";
//nineTower[i][j] = "(" + i + ":" + j + ")";
}
}
}
// 取值
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.print(nineTower[i][j]);
}
System.out.println("");
}
}
}
4.5 冒泡排序
public class Demo {
public static void main(String[] args) {
// 数组
int[] nums = {1,4,3,5,2};
// 自动排序(从小到大)-冒泡排序
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length - 1 - i; j++) {
int num1 = nums[j];
int num2 = nums[j + 1];
if(num1 > num2){
nums[j] = num2;
nums[j + 1] = num1;
}
}
}
for (int num : nums) {
System.out.println(num);
}
}
}
4.6 选择排序
public class Demo {
public static void main(String[] args) {
// 数组
int[] nums = {1, 4, 3, 5, 2};
for (int j = 0; j < nums.length; j++) {
int maxIndex = 0;
for (int i = 1; i < nums.length - j; i++) {
if (nums[i] > nums[maxIndex]) {
maxIndex = i;
}
}
int num1 = nums[nums.length - j - 1];
int num2 = nums[maxIndex];
nums[maxIndex] = num1;
nums[nums.length - j - 1] = num2;
}
for (int num : nums) {
System.out.println(num);
}
}
}
4.7 二分法查找
public class Demo {
public static void main(String[] args) {
// 有序数据,二分法查找
int[] nums = {1, 2, 3, 4, 5, 6, 7};
// 查询目标
int targetNum = 6;
int start = 0;
int end = nums.length - 1;
int middle = 0;
while (start <= end) {
middle = (start + end) / 2;
if (nums[middle] > targetNum) {
end = middle - 1;
} else if (nums[middle] < targetNum) {
start = middle + 1;
} else {
break;
}
}
System.out.println("数据在数组的位置:" + middle);
}
}
4.8 字符串
字符串、字符、字节
public class Demo {
public static void main(String[] args) throws UnsupportedEncodingException {
// 字符串:连续字符组合形成的数据整体
// java.lang.String
// 字符串、字符、字节
// 字符串的使用
String name1 = new String("zhangsan");
// 可以简写,new的过程JVM会自动帮助完成
String name2 = "zhangsan";
// 在java中使用简写方式,如果字符串相同,那引用的都是同一个对象
// 字符串对象的构建方式
char[] c = {'a','中','国'};
byte[] b = {-28,-72,-83,-27,-101,-67};
String s1 = new String(c);
String s2 = new String(b, "UTF-8");
System.out.println(s1);
System.out.println(s2);
// 转义字符:\" => 文字内容的双引号
System.out.println("\"");
System.out.println("\t");
System.out.println("\n");
System.out.println("\\");
}
}
4.9 字符串拼接
public class Demo {
public static void main(String[] args) throws UnsupportedEncodingException {
// 拼接:将多个字符串链接在一起
String s = "a" + "b"; // "a" + "b"产生新的字符串"ab"
String s1 = "ab";
System.out.println(s.hashCode());
System.out.println(s.hashCode());// s与s1内存地址是相同的
// 这里的+是JVM虚拟机为了简化字符串拼接提供的一个特殊运算符号,和数字计算+不一样
String s2 = "abc" + 1 + 2;//JVM检测到字符串+数字,会自动把加号后也转换成字符串
String s3 = 1 + "abc";//只要+两边有字符串,就会全都转换成字符串
String s4 = 1 + 2 + "abc"; //3abc
// concat()拼接字符串
System.out.println("abc".concat("def"));
}
}
4.10 字符串比较
public class Demo {
public static void main(String[] args) throws UnsupportedEncodingException {
// 字符串比较
String a = "a";
String b = "b";
// 相等:equals(字符串内每一个字符都相等)
System.out.println(a.equals(b));
// 忽略大小写相对
System.out.println(a.equalsIgnoreCase(b));
// 比较大小(比较字节数大小)
// i = 正数 a > b
// i = 负数 a < b
// i = 0 a = b
int i = a.compareTo(b);
System.out.println(i);
// 忽略比较大小
System.out.println(a.compareToIgnoreCase(b));
}
}
4.11 字符串截断
public class Demo {
public static void main(String[] args) throws UnsupportedEncodingException {
// 字符串截断操作:截取字符串的操作
String s = "Hello Word";
// 子字符串
// substring()用于截取字符串,需要传递两个参数
// 参数1:截取初始位置(索引)包含
// 参数2:截取结束位置(索引)不包含
String s1 = s.substring(0, 3);
System.out.println(s1);
// 从指定位置截取到最后
System.out.println(s.substring(3));
// 分解字符串:根据指定的规则对字符串进行分解,可以将一个完整的字符串分解成几个部分。
String[] s2 = s.split(" ");//按空格分解
for (String s3 : s2) {
System.out.println(s3);
}
// trim:去掉字符串首尾空格
String test = " abcd ";
System.out.println("1" + test.trim() + "1");
}
}
4.12 字符串替换
public class Demo {
public static void main(String[] args) throws UnsupportedEncodingException {
// 字符串的替换
String s1 = "Hello Word zhangsan";
System.out.println(s1.replace("Word", "Java"));
// 如果一个字符串重复出现
String s2 = "Hello WordWord";
System.out.println(s2.replace("Word", "Java"));
// replaceAll()按照指定的规则进行替换
System.out.println(s1.replaceAll("Word|zhangsan", "java"));
}
}
4.13 字符串大小写转换
public class Demo {
public static void main(String[] args) throws UnsupportedEncodingException {
// 字符串的大小写转换
String s = "Hello Word";
System.out.println(s.toLowerCase());//全变小写
System.out.println(s.toUpperCase());//全变大写
// 按驼峰标识改变
String className = "user";
String s1 = className.substring(0,1);//u
String s2 = className.substring(1);//ser
System.out.println(s1.toUpperCase() + s2);//User
}
}
4.14 字符串查询
public class Demo {
public static void main(String[] args) throws UnsupportedEncodingException {
// 字符串的查询
String s = "Hello World";
char[] chars = s.toCharArray();
byte[] bytes = s.getBytes("UTF-8");
// charAt可以传递索引定位字符串中指定位置字符
System.out.println(s.charAt(1));
//indexOf()判断(字符、字符串)在字符串中第一次出现位置
System.out.println(s.indexOf('o'));
// lastIndexOf()判断(字符、字符串)在字符中串最后次出现位置
System.out.println(s.lastIndexOf('o'));
// 是否包含指定的字符串,返回布尔类型
System.out.println(s.contains("Hello"));
// 判断字符串是否以指定的数据开头,返回布尔类型
System.out.println(s.startsWith("Hello"));
// 判断字符串是否以指定的数据结尾,返回布尔类型
System.out.println(s.endsWith("World"));
// 判断字符串是否为空,返回布尔类型(空格是特殊字符,看不见,但是不为空)
System.out.println(s.isEmpty());
}
}
4.15 StringBuilder
public class Demo {
public static void main(String[] args) throws UnsupportedEncodingException {
// StringBuilder:构建字符串(底层使用数组方式,效率比String高)
// 在频繁拼接推荐使用StringBuilder
StringBuilder s = new StringBuilder();
// 拼接字符串
s.append("a");
s.append("b");
// 打印
System.out.println(s.toString());
// 当前长度
System.out.println(s.length());
// 当前字符串反转
System.out.println(s.reverse());
// 向指定位置插入
System.out.println(s.insert(1, "c"));
}
}
4.16 包装类
public class Demo {
public static void main(String[] args) throws UnsupportedEncodingException {
// 常见类和对象
// byte short int long
// float double
// char
// boolean
// Java为了优化基本数据类型,提供了特殊的类与之对应
// 包装类
Byte b = null;//byte
Short s = null;//short
Integer i = null;//int
Long l = null;//long
Float f = null;//float
Double d = null;//double
Character c = null;//char
Boolean bln = null;//boolean
// 转换关系
int i1 = 10;
// 装箱
i = Integer.valueOf(i1); // 将基本数据类型转换为包装类型(装箱)
i = i1;// 装箱操作十分频繁,JVM简化操作(自动装箱)
// 拆箱
int i2 = i.intValue();//把包装类型转换成基本数据类型(拆箱)
i2 = i;// 拆箱操作十分频繁,JVM简化操作(自动拆箱)
// 包装类除了拆箱装箱,还可以转换成别的数据类型
}
}
4.17 日期类Date
public class Demo {
public static void main(String[] args) throws UnsupportedEncodingException, ParseException {
// Date:日期类
// 获取当前时间,(时间戳)单位:毫秒(从1970年1月1日到现在的long类型整数数值)
System.out.println(System.currentTimeMillis()); // 这个时间戳对用户不友好
// Date:日期类(java.util.Date)
// Calendar:日历类
Date date = new Date();
System.out.println(date);
// 专门对日期格式化操作的类
// Java格式化日期格式
// y:年 yyyy(Y):一年内的第几周
// m:分钟 mm(M):月份 MM
// d:一个月中的日期 dd(D):一年中的日期
// h:12进制小时hh(H):24进制小时HH
// s:秒ss(S):毫秒
// 日期--->String
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format = dateFormat.format(date);
System.out.println(format);
// String--->日期
String dateString = "2022-01-01 19:23:12";
Date parseDate = dateFormat.parse(dateString);
System.out.println(parseDate);
// 根据时间戳构建指定的日期对象
date.setTime(System.currentTimeMillis());
// 获取时间戳
System.out.println(date.getTime());
// 比较时间顺序(判断两个date,date的格式必须一致,不一致就会报错)2022-12-20 19:30:40 与 2022-01-01格式不一致
System.out.println(parseDate.before(date));
}
}
4.18 日历类Calendar
public class Demo {
public static void main(String[] args) throws Exception {
// 日历类:Calendar
Calendar instance = Calendar.getInstance();
// 获取年
System.out.println(instance.get(Calendar.YEAR));
// 获取月(月是从0开始11结束)
System.out.println(instance.get(Calendar.MONDAY));
// 获取日
System.out.println(instance.get(Calendar.DATE));
// 星期(周日1 周一2 周二3)
System.out.println(instance.get(Calendar.DAY_OF_WEEK));
// 传入指定日期
instance.setTime(new Date());
// 可以手动对年、月、日 加减
instance.add(Calendar.YEAR,1);
}
}
4.19 打印日历
public class Demo {
public static void main(String[] args) throws Exception {
// 打印日历
System.out.println("周一\t周二\t周三\t周四\t周五\t周六\t周日");
// 获取当前日期的日历对象
Calendar firstDate = Calendar.getInstance();
// 把日历对象设定当前月的第一天
firstDate.set(Calendar.DAY_OF_MONTH, 1);
// 获取当前月最大的日期
int maxDay = firstDate.getMaximum(Calendar.DAY_OF_MONTH);
for (int i = 0; i < maxDay; i++) {
// 当前日期是周几
int weekX = firstDate.get(Calendar.DAY_OF_WEEK);
// 当前日期是几号
int monthY = firstDate.get(Calendar.DAY_OF_MONTH);
if (i == 0) {
if (weekX == Calendar.SUNDAY){
for (int j = 0; j < 6; j++) {
System.out.print("\t");
}
System.out.println(monthY);
}else {
// 周日1 周一2 周二3
for (int j = 0; j < weekX - 2; j++) {
System.out.print("\t");
}
System.out.print(monthY);
System.out.print("\t");
}
} else {
//不是一号的场合
if (weekX == Calendar.SUNDAY){
System.out.println(monthY);
}else {
System.out.print(monthY);
System.out.print("\t");
}
}
// 打印日历后,增加一天
firstDate.add(Calendar.DATE,1);
}
}
}
4.20 工具类
// 字符串工具类
// 1. 工具类不应该创建对象才能使用,也就意味着,可以直接使用类中的属性和方法,一般都声明为静态的
// 2. 工具类对外提供的属性和方法都应该是公共的
// 3. 为了使用者开发方便,应该尽量提供丰富的方法和属性
class StringUtil {
// 非空判断
public static boolean isEmpty(String str) {
// 如果字符串为null 为空
// if (str == null) {
// return true;
// }
// 如果字符串为空字符串, 为空
// if ("".equals(str)) {
// return true;
// }
// 全是空格也是空
// if ("".equals(str.trim())) {
// return true;
// }
if (str == null || "".equals(str.trim())) {
return true;
}
return false;
}
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
}
// 生成随机字符串
public static String makeString(){
return UUID.randomUUID().toString();
}
public static String makeString(String from,int len){
if(len < 1){
return "";
}else {
char[] chars = from.toCharArray();
StringBuilder str = new StringBuilder();
for (int i = 0; i < len; i++) {
Random random = new Random();
int j = random.nextInt(chars.length);
char c = chars[j];
str.append(c);
}
return str.toString();
}
}
// 转换字符串 ISO8859-1 转换成 UTF-8
public static String transform(String source,String encodeFrom,String encodeTo) throws UnsupportedEncodingException {
byte[] bytes = source.getBytes(encodeFrom);
return new String(bytes,encodeTo);
}
// 转换字符串到日期 日期在转会字符串
public static Date parseDate(String dateString,String format) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.parse(dateString);
}
public static String formatDate(Date date,String format) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
}
}
4.21 比较(等于)
public class Demo {
public static void main(String[] args) throws Exception {
// 等于
// 基本数据类型,双等号比较数值
int i = 10;
int j = 10;
System.out.println(i == j);
double d = 10.0;
System.out.println(i == d);
// 引用数据类型,双等号比较内存地址
String s = "abc"; // 储存在字符串常量池
String s1 = "abc";// 储存在字符串常量池
String s2 = new String("abc"); // 新构建的对象
System.out.println(s == s1); // 内存地址相同
System.out.println(s == s2); // 内存地址不相同
// 如果想比较内容,不比较内存地址
System.out.println(s.equals(s2));
// 自定义对象比较
User user1 = new User();
User user2 = new User();
System.out.println(user1 == user2);//false
System.out.println(user1.equals(user2));//false
// 自定义对象的equals方法来自父类Object,当用户没有重写equals,本质是双等号比较内存地址
// public boolean equals(Object obj) {
// return (this == obj);
// }
// 包装类型
Integer i1 = 100;
Integer i2 = 100;
System.out.println(i1 == i2); // true
i1 = 1000;
i2 = 1000;
System.out.println(i1 == i2); // false
i1 = 150;
i2 = 150;
System.out.println(i1 == i2); // false
// 在Integer中有缓存数据,默认-128到127
// 结论:包装类型比较不要用双等号,使用equals()
}
}
class User {
// 重写equals方法
@Override
public boolean equals(Object obj) {
// 不再使用父类提供的方法,使用用户自己定义的判断逻辑
return true;
}
// 还会重写另一个方法hashCode
@Override
public int hashCode() {
return 1;
}
}