JavaSE基础(W4)总结
day1
java.lang.Object类:
java.lang.Object类:
Object 是类层次结构的根类。
每个类都使用 Object 作为超类(父类),所有对象(包括数组)都实现这个类的方法。
常用功能:
public final Class getClass(){} :
获取某个类或者接口的字节码文件对象 : class 包名.类名
public int hashCode() :获取某个对象的哈希码值
( 可以看成类似于 "地址值的东西")
public String toString():表示一个对象的 "文本表现形式"
public boolean equals(Object obj):使用某个对象与此对象进行比较!
protected Object clone() throws CloneNotSupportedException :克隆
子类也称为(派生类)
Object类的public boolean equals(Object obj)方法
Object类的public boolean equals(Object obj)方法
使用其他对象和此对象进行比较
==:连接是两个基本数据类型,比较的是数据值是否相同
如果连接的是两个引用数据类型,比较的是地址值是否相同
equals方法:
Object类的equals方法默认比较的两个对象的地址值是否相同,
如果比较的内容相同,建议子类重写Object的equals方法
注意:
当此方法被重写时,通常有必要重写 hashCode 方法
建议:所有的子类重写equals方法()同时重写hashCode()方法,比较的时候就比较的是两个对象的内容是否相同
"内容",对象的成员信息是否一致!,如果一致就是true
protected Object clone()克隆
protected Object clone()
throws CloneNotSupportedException:克隆:创建对象并返回此对象的"副本"!
浅克隆!
Object 类的 clone 方法执行特定的复制操作。首先,如果此对象的类不能实现接口 Cloneable,则会抛出 CloneNotSupportedException。
注意,所有的数组都被视为实现接口 Cloneable
Day2
1.Scanner字符
构造方法:
public Scanner(InputStream source):
创建一个文本扫描器,需要传递字节输入流,形式参数是一个抽象类,需要抽象类子类对象
获取功能
public int nextInt() :将下一个录入的标记为int类型
判断功能:
public boolean hasNextXXX()
判断是否为xxx类型
public boolean hasNextLine():判断录入的是否为String
public boolean hasNextInt() :判断录入的是否为int
创建键盘录入对象
System类有一个标准输入流,标准输出流
in,out这些成员变量
public static final InputStream in ;标准输入流
public static final PrintStream out ;标准输出流
InputStream is = System.in;//导包,import java.io.InputStream;
Scanner sc = new Scanner(is);
//提升并录入数据
System.out.println("输入一个数据");
//判断数据
if (sc.hasNextInt()) {//判断输入的数据是否为int类型
int a = sc.nextInt();
PrintStream ps = System.out;//PrintStream:字节打印流:属于 "字节输出流的一种"
ps.println("输出int的数据是:"+a);
}else if(sc.hasNextLine()){
String a = sc.nextLine();
// PrintStream ps = System.out;
// ps.println("录入的字符数据是:"+a);//两种都可以使用
System.out.println("录入的字符数据是:"+a);
}else if (sc.hasNextDouble()){
double a = sc.nextDouble();
System.out.println("录入的double值为:"+a);
}
}
}
如果录入的结果数据类型和接收的类型不匹配
java.util.InputMismatchException:输入类型不匹配异常
//System.err.println("这是错误输出流"); 将out换位err打印的字体将变成红色
String字符
String s = new String("hello") ;
String s = "hello" ; 推荐(使用)
两个区别是什么? 分别创建了几个对象
前者:要在堆内存中产生空间地址,并且要常量标记:"hello" , 两个 (堆,常量池)
后者:创建一个对象,将常量赋值给变量,直接现在常量池 中找是否存在这个常量值,存在,直接返回值地址;不存在
在常量池中开辟空间!
前者和共同点:都是创建一个字符串对象:"hello",推荐使用后者,节省内存空间!
public class StringDemo2 {
public static void main(String[] args) {
String s1 = "hello" ;
String s2 = new String("hello") ;
System.out.println(s1 == s2); //比较地址值
System.out.println(s1.equals(s2));
//String底层重写了Object类的equals方法以及hashCode(),比较的是两字符串对象中存储的字符序列是否一样
}
}
2.构造方法
public String()空参构造(不建议使用:是一个空字符序列)
String(byte[] bytes) :使用平台默认解码集进行解码
String(byte[] bytes,字符集) :使用指定字符集集进行解码
public String(byte[] bytes,int offset,int length):将一个部分字节数组字符串
public String(char[] value):构造一个字符串对象,传递一个字符数组
public String(char[] value,int offset,int count):将字符数组的某个位置开始指长度的内容转换成字符串对象
public String(String original):传入指定的字符串值,构造一个字符串对象!
字符的获取功能:
int length();字符串的特有功能,获取字符串长度.
字符串有转换功能:
byte[]getBytes(); 将字符串转换为数组,空参为默认编码集.
byte[] getBytes(字符集) :将字符串转换为字节数组,使用指定字符集编码
String s = "" ;
String s = null ; 空值,没有对象,这两者不一样,上面的值为"空",下面为null
测试构造方法:
测试构造方法:
public class StringDemo {
public static void main(String[] args) throws UnsupportedEncodingException {
//测试构造方法
// public String()
String s1 = new String() ; //String s1 = "" ;
//String s2 = null ;
System.out.println(s1);//字符为"空",但不是null
System.out.println(s1.length());//输出字符长度0
字符的编码
字符的编码:就是将能看懂的东西转为看不懂的
String s2 = "我爱你中国" ;
//String的转换功能:getBytes()---->byte[] :平台默认编码集编码: utf-8 (一个中文三个字节)
byte[] bytes = s2.getBytes();
// byte[] bytes = s2.getBytes("GBK"); //GBK一个中文两个字节,编码用什么转码就用什么,否则会乱码
//System.out.println(bytes);
//java.util.Arrays:针对数组操作的工具类(提供:排序,,搜索,将数组转换成的功能)
//public static String toString(byte[] a):重载的方法:可以将任何数组转换成String
String byteArray = Arrays.toString(bytes);
System.out.println(byteArray);
将"我爱你中国"编译成看不懂的
输出:[-26, -120, -111, -25, -120, -79, -28, -67, -96, -28, -72, -83, -27, -101, -67]
三个数字对应一个汉字,因为UTF-8是三个字节
字符的解码
//解码:利用String类型的构造方法String(byte[] bytes):默认平台解码集解码
String s3 = new String(bytes) ;//utf-8解码,三个字节
// String s3 = new String(bytes,"GBK") ;GBK两个字节,用那个编译就用什么解码,否则会乱码
System.out.println(s3);
常见的字符集:
常见的字符集:
GBK :中国的中文编码表 (一个中文对应两个字节)
GB2312:GBK的升级版,可以提供更多的中文字符
utf-8:一个中文对应3个字节
iso-8859-1:拉丁文码表
big-5:大五码:港澳地区:繁写字体
unicode:国际编码表
字节数组截取
byte[] bytes2= {97,98,99,100,101} ;
String s4 = new String(bytes2) ; //字节数需要找对应的ASCII码表
System.out.println(s4); //输出a,b,c,d,e,因为对应ASCII
System.out.println(s4.length());//长度为5
// public String(byte[] bytes,int offset,int length):将一个部分字节数组字符串
String s5 = new String(bytes2,2,2) ;//截取字符串,从第二个开始,截取长度为2
System.out.println(s5); //截取后输出c,d
System.out.println(s5.length()); //输出长度为2,因为值截取了两个
字符串截取
//public String(char[] value):构造一个字符串对象,传递一个字符数组
char[] chs = {'我','爱','你'} ;
String s6 = new String(chs) ;
System.out.println(s6); //输出:我爱你
System.out.println(s6.length());//长度为:3
//public String(char[] value,int offset,int count)
String s7 = new String(chs,0,2) ; //截取字符串,从0开始,截取两个
System.out.println(s7+"---"+s7.length()); //输出:我爱---2 长度为2
System.out.println("-----------------------------------");
// public String(String original):
String s8 = new String("hello") ;//传入hello
System.out.println(s8+"---"+s8.length());//输出hello,长度为5
Day3
==和equals的区别
==和equals的区别
==:连接的引用类型变量:比较的是地址值是否一样
equals:默认比较的是两个对象的地址值是否相同,只要他重写了Object的equals方法,比较的是对象中的内容是否相同
String类本身重写了equals方法
将常量赋值给String变量以及new String("常量")区别
前者是在常量池中去寻找是否存在这个常量,有就返回它常量池中的这个常量地址;否则,就在常量池中开辟空间!
后者:是在堆内存中开辟空间,同时字符串常量标记,需要在常量池中寻找这个常量
字符串变量相加:先开空间,不会直接先拼接;
而字符串常量相加,直接先相相加,然后看结果是否在常量池中有,如果存在,直接返回当前这个地址;否则开辟的新的空间 String s1 = "hello" ;
String s2 = "world" ;
String s3 = "helloworld" ;
System.out.println((s1+s2)==s3);//false
System.out.println((s1+s2).equals(s3));//true
System.out.println(("hello"+"world")==s3);//true
System.out.println(("helloworld").equals(s3));//true
字符换特点及字符串应用
字符串的特点:是常量,一旦被创建,其值不能更改
字符串中相关的成员方法:
获取功能:
public char charAt(int index):获取指定索引处的字符内容
public String concat(String str):将指定的字符串和当前字符串进行拼接,获取一个新的字符串
public int indexOf(int ch):获取指定字符在此字符串中第一次出现是索引值
public int lastIndexOf(int ch):获取指定字符在此字符串中最后一个次出现的索引值
public int length():获取字符串长度
public String[] split(String regex):字符串拆分(分割功能)--->获取字符串数组
获取指定索引处的字符内容charAt(int index)
定义一个字符串直接赋值
String str = "helloworldJavaEE" ;
//public char charAt(int index):获取指定索引处的字符内容
System.out.println(str.charAt(4));//获取索引4的值输出"o"
System.out.println(str.charAt(8));//获取索引8的值输出"i"
拼接功能concat(String str)
// public String concat(String str):将指定的字符串和当前字符串进行拼接,获取一个新的字符串
int a = 100 ;//传统赋值"+"
System.out.println(""+a); //"100"
System.out.println(str.concat("你好"));//输出:helloworldJavaEE高圆圆
获取第一次出现的索引值indexOf(int ch)
//public int indexOf(int ch):获取指定字符在此字符串中第一次出现是索引值
System.out.println(str.indexOf('l'));//"l"第一次出现的索引值是2
获取最后一次出现的索引值lastIndexOf(int ch)
public int lastIndexOf(int ch):获取指定字符在此字符串中最后一个次出现的索引值System.out.println(str.lastIndexOf("a"));//最后一次出现的索引值是13
获取字符串长度length():
//public int length():获取字符串长度
System.out.println(str.length());//字符长度为16
字符串拆,获取字符串数组split(String regex)
String s = "php-javaee-python-go-r-c-c#-c++" ;
//使用-拆分
String[] strArray = s.split("-");
for (int i = 0; i <strArray.length ; i++) {
System.out.print(strArray[i]+"\t");
}
拆分输出:php javaee python go r c c# c++
字符串的判断功能
public boolean equals(Object anObject):判断当前字符串和此传递进来的字符串进行对比:内容是否相同
public boolean equalsIgnoreCase(String anotherString):不区分大小写,对比的字符串内容
public boolean contains(CharSequence s):判断是否包含指定的字符值
public boolean isEmpty():判断字符串 是否为空内容
boolean startsWith(String prefix) :判断以指定的字符串开头
boolean endsWith(String suffix):判断以指定的字符串结尾
equals(Object anObject)判断字符串内容
//创建一个字符串
String s = "helloJavaEE" ;
//public boolean equals(Object anObject): 区分大小写的(如果为字符串类型)
System.out.println(s.equals("HELLOJavaEE"));//false
System.out.println(s.equals("helloJavaEE"));//true
equalsIgnoreCase(String anotherString).判断内容相等(不区分大小写)
public boolean equalsIgnoreCase(String anotherString):不区分大小写,对比的字符串内容
System.out.println(s.equalsIgnoreCase("HELLOJavaEE"));//true
contains(String s) 判断是否包含指定的子字符串
//public boolean contains(String s):判断是否包含指定的子字符串
System.out.println(s.contains("hello"));//true
System.out.println(s.contains("ak47"));//false
isEmpty()判断字符串内容是否为空
//空内容输出true,不是空内容输出flase,
s = "" ;
//空字符串: 空字符序列
System.out.println(s.isEmpty());
s = null ; //空对象
// System.out.println(s.isEmpty());
if(s!=null){
System.out.println(s.isEmpty());
}else{
System.out.println("对不起,没有字符串对象存在");
}
可以利用判断语句进行判断
startsWith(String prefix) :判断以指定的字符串开头
System.out.println(s.startsWith("hel"));//区分大小写
endsWith(String suffix):判断以指定的字符串结尾
System.out.println(s.endsWith("ee"));//区分大小写
String类的截取功能
public String substring(int beginIndex) :从指定的位置开始进行截取,默认截取到末尾为止
public String substring(int beginIndex,int endIndex)
获取一个新的字符串,从指定位置开始,到指定位置结束(包前不包后)(endIndex-1)
substring(int beginIndex)截取字符串
String s = "helloworld" ;
String s2 = s.substring(5);//从指定位置进行截取,直到末尾
System.out.println(s2);//输出world,索引值5以后的字符(包含索引5)
String s3 = s.substring(4, 8);//从指定位置截取,到指定位置结束,末尾角标-1,才是取到的字符
System.out.println(s3);()//输出索引值4-7之间的字符
String类的 其他功能
替换功能
public String replaceAll(String regex,
String replacement):替换所有:参数1为:匹配的正则表达式的子字符串
参数2:要替换的内容
邮箱: 数字或者字母@数字或者字母.com
public String replace(char oldChar,
char newChar):将oldChar使用newChar进行替换
public String replace(String target,
String replacement) :将指定target子串使用指定 replacement子串进行替换
去重两端空格
public String trim():应用场景:
在IO中传输一些字符串数据的时候,防止前部和尾部存在空格字符,导致io异常,将字符串先去除两端空格
"hello"
" hello "
按照字典顺序比较
public int compareTo(String anotherString)
替换功能replaceAll(String regex, String replacement)
//创建一个字符串
String s = "helloworldjavaee" ;
String s2 = s.replace('l', 'k');//将字符串中出现的"i"替换为"k"输出hekkoworkdjavaee
System.out.println(s2);
replace(char oldChar, char newChar):将oldChar使用newChar进行替换
String s3 = s.replace("worldjavaee", "你好");
System.out.println(s3);//将"worldjavaee"替换为"你好",输出"hello你好"
trim()去除两端空格
在IO中传输一些字符串数据的时候,防止前部和尾部存在空格字符,导致io异常,将字符串先去除两端空格
String str = " helloworld " ;
System.out.println("---"+str+"-----");//输出:--- helloworld -----中间有空格
String str2 = str.trim();
System.out.println("---"+str2+"-----"); //---helloworld-----中间没有空格
compareTo(String anotherString):按照字典顺序比较
//public int compareTo(String anotherString):按照字典顺序比较
String strs1 = "hello" ;
String strs2 = "abc" ;
System.out.println(strs1.compareTo(strs2));// abcdefgh
StringBuffer的构造方法:
StringBuffer:线程安全的可变字符序列
一个类似于 String 的字符串缓冲区,但不能修改
StringBuffer是一个可变的字符序列
StringBuilder:jdk5以后提供的单线程程序中去替代StringBuffer使用的,不同步,执行效率高
与StringBuffer有兼容的API(所有的功能都相同)
StringBuffer的构造方法:
public StringBuffer():空参构造,创建一个空参的字符串缓冲区对象,16个初始容量字符 (默认容量足够大)
public StringBuffer(String str):构造一个字符串缓冲对象,并且为其声明一个字符序列 str
public StringBuffer(int capacity):构造一个字符串缓冲区对象,指定初始容量
获取功能:
int length():获取缓冲区中的字符长度
public int capacity():获取字符串缓冲区中的容量
StringBuffer()的空参构造,(默认16个初始容量字符)
// public StringBuffer():空参构造,创建一个空参的字符串缓冲区对象,16个初始容量字符
StringBuffer sb = new StringBuffer() ; //其实他的默认初始化容量是通过它父类的有参构造通过字符数组操作的!
System.out.println(sb);
System.out.println(sb.length());//输出0,因为长度为0
System.out.println(sb.capacity());//输出16,因为默认16个初始容量字符
StringBuffer()字符长度及字符容量
//public StringBuffer(String str)
StringBuffer sb2 = new StringBuffer("abc") ;
//底层---父类的构造方法:使用创建字符串数组,并且同时还需要将字符串追加缓冲区中:
// append():同步方法:(线程安全方法)
System.out.println(sb2); //输出abc
System.out.println(sb2.length());//字符长度为3
System.out.println(sb2.capacity());//字符 缓冲区容量19
StringBuffer sb3 = new StringBuffer(50) ;//设置容量为50
System.out.println(sb3);输出""空的
System.out.println(sb3.length());//长度为0因为没有字符
System.out.println(sb3.capacity());//输出50,因为设置长度为50,
StringBuilder用来替换StringBuffer
"hello"+s1 ;---->使用反编译工具:new StringBuilder().append("hello").append(s1) ;
StringBuffer的添加功能:
StringBuffer append(任何数据类型):将指定的内容追加到字符串缓冲区中,返回字符串缓冲区本身
public StringBuffer insert(int offset,String str)
可以将任意类型元素插入到指定位置处
删除功能:
public StringBuffer deleteCharAt(int index):删除指定索引出的字符序列
public StringBuffer delete(int start,int end):
删除从指定位置开始到指定位置结束的字符序列,但是不包含end,包含的end-1的位置
.append():将指定的内容追加到字符串缓冲区中,返回字符串缓冲区本身
//创建一个空字符序列的字符串缓冲区对象
StringBuffer sb = new StringBuffer() ;
System.out.println(sb); sb.append(100).append('a').append(13.56).append(true).append("hello").append("javaee");
System.out.println(sb);//输出100a13.56truehellojavaee
insert(int offset,String str) 将任意类型元素插入到指定位置处
StringBuffer sb2 = new StringBuffer() ;
sb2.append("hello") ;
sb2.append("world") ;
sb2.append("javae") ;
sb2.insert(5,"你好") ;
System.out.println(sb2);//输出:hello你好worldjavae
deleteCharAt(int index):删除指定索引字符
StringBuffer sb3 = new StringBuffer() ;
sb3.append("hello") ;
sb3.append("world") ;
System.out.println(sb3);//输出:helloworld
System.out.println(sb3.deleteCharAt(2));//需求:删除第一个l字符是,输出heloworld
System.out.println(sb3.deleteCharAt(1));//需求:删除e这个字符,输出hloworld
删除从指定位置开始到指定位置结束的字符序列,但是不包含end,包含的end-1的位置
//public StringBuffer delete(int start,int end):返回值都是字符串缓冲区本身
System.out.println(sb3.delete(4,9))//输出:hlow
StringBuffer的截取功能:
返回被截取的内容!
public String substring(int start):从指定位置开始截取到末尾,返回一个新的字符串
public String substring(int start,int end):从指定为值到end-1位置,返回值一个新的字符串
StringBuffer sb3 = new StringBuffer() ;
sb3.append("hello") ;
sb3.append("android") ;
sb3.append("Javaee") ;
String substring = sb3.substring(5);//输出androidJavaee,将索引值(包括)5以前的字符删除
System.out.println(substring);
String substring1 = sb3.substring(5,10) ;//输出andro,索引值5以前,10以后的字符删除
System.out.println(substring1);
String<---->StringBuffer:如何转换
在实际开发中,经常需要将A类型转换成B类型,因为我可能需要使用B类中的功能!
但是,有的时候就将B类型--->A类型,结果最终可能需要A类型!
String--->StringBuffer
//String--->StringBuffer
//方式一
String s = "hello" ;
//定义StringBuffer类型变量
StringBuffer sb = new StringBuffer(s) ;
System.out.println(sb);//输出hello(StringBuffer类型)
//方式二使用StringBuffer的空参构造,+append(元素)
StringBuffer sb2 = new StringBuffer() ;
sb2.append(s) ;
System.out.println(sb2);//输出hello(StringBuffer类型)
StringBuffer--->String
//方式一: String的构造方法:public String(StringBuffer buffer)
StringBuffer buffer = new StringBuffer("javaee") ;//类型为StringBuffer类型
String str = new String(buffer) ;
System.out.println(str);//输出String类型的:javaee
//方式2:
//public String toString()
String str2 = buffer.toString();
System.out.println(str2);//输出String类型的:javaee
StringBuffer的反转功能reverse()
Scanner sc = new Scanner(System.in) ;
System.out.println("请输入 一个字符串:");
String line = sc.nextLine() ;
//反转--->StringBuffer
StringBuffer buffer = new StringBuffer(line) ;
buffer.reverse() ;
//在将StringBuffer--->String
String s = buffer.toString();
System.out.println(s);//输入什么就讲什么字符反转
StringBuffer和String 作为方法的形式参数有什么区别
方法的形式参数:基本类型
形参的改变不影响实际参数
引用类型
形参的改变直接影响实际参数
String也是引用类型(特殊的引用类型),特点:是一个常量,一旦被创建,其值不能被更改 String s ="abc" ;
String类型作为形式参数,效果和基本类型一致!
从概念上讲:
tringBuffer:可变的字符序列 (线程安全的类)
String::是一个常量,一旦被创建,其值不能被更改
Character
Java中基本数据类型:四类八种,都会对应一个引用类型(JDK5以后新特性:自动拆装箱)
基本类型 对应的引用类型
byte Byte
short Short
int Integer
long Long
float Float
double Double
char
boolean Boolean
Character:包含了一个char的值
构造方法
public Character(char value) :创建Character类对象,参数为char类
Character character = new Character((char)97) ;
System.out.println(character);//输出为"a",因为97对应的ASCII码表就是"a"
大小写区分及数字判断
public static boolean isDigit(char ch):判断这个ch字符是否为数字
public static boolean isLowerCase(char ch):判断这个ch字符是否为小写字母字符
public static boolean isUpperCase(char ch):判断这个ch字符是否为大写字母字符
System.out.println(Character.isDigit('0'));
System.out.println(Character.isUpperCase('A'));
System.out.println(Character.isLowerCase('a'));
求进制Integer
Integer类的静态的功能:
public static String toBinaryString(int i):将十进制转换成二进制(以字符串形式体现)
public static String toOctalString(int i):转换八进制(返回String)
public static String toHexString(int i):转换成十六进制(返回String)
Integer类:
成员变量:
public static final int MIN_VALUE:包装了int类型的最小值
public static final int MAX_VALUE:包装了int类型的最大值
System.out.println(Integer.toBinaryString(100));//100对应二进制数为1100100
System.out.println(Integer.toOctalString(100));//100对应八进制数为144
System.out.println(Integer.toHexString(100));//100对应十六进制数为64
System.out.println(Integer.MIN_VALUE);//最小值-2147483648
System.out.println(Integer.MAX_VALUE); //最大值 2147483647
Integer构造方法
构造方法
public Integer(int value):将int类型的数据包装为Integer类型
public Integer(String s) throws NumberFormatException :将字符串值包装为Integer类型
此s参数必须为数字字符串,否则程序出现 NumberFormatException(数字格式化异常)
//创建Integer类对象
int number = 100 ; //基本数据类型
Integer integer = new Integer(number) ;//引用类型,内部默认拆箱后计算,然后装箱
System.out.println(integer);
// String s = "hello" ;//当s被解析时,如果不是int值的话,就会出现数字格式化异常
String s = "20" ;
Integer integer2 = new Integer(s) ;
System.out.println(integer2) ;//拆箱计算后,装箱
Integer拆装箱
Jdk5以后新特性:
静态导入,自动拆装箱,增强for循环,可变参数,枚举...
自动拆装箱:
装箱: 基本数据类型 会自动的包装为对应的引用类型
拆箱: 引用类型会自动的转换为基本数据类型
int--->Integer
Integer--->in
int num = 200 ;
//创建Integer类对象
Integer i = new Integer(num) ;
i += 100 ;//计算式系统默认将Integer拆箱为int,计算完毕后再装箱为Integer类型
//源码,:Integer.valueOf(i.intValue() + 100);
System.out.println(i);
Integer内部缓存区
Integer类中存在一个:内部缓存区 IntegerCache(Integer的成员内部类): 范围:-128~127
当赋值的时候要考虑值是否再范围内:范围:-128~127
如果不在内部缓存区 的范围内(-128~127):会重新开辟空间new Integer
如果在内部缓存区中:直接从缓冲区(Integer的静态的成员内部类) :直接从缓存区中取值!
Integer i5 = 128 ;
Integer i6 = 128 ;
System.out.println(i5 == i6);//false,因为值不在范围内,要开辟新空间
System.out.println(i5.equals(i6));
Day4
int类型和String类型的相互转换
int--->String
Integer.toString(int值)--->String
String---->int
Integer.parseInt(数字字符串)---->int
int转换String
//方式1:空串拼接(最简单的)
int a = 100 ;//定义一个int类型变量
String s = "" ;
String result = s + a ;
System.out.println("result:"+result);
//方式2:包装为Integer----->String
Integer i = new Integer(a) ;
//String toString()
String result2 = i.toString();
System.out.println(result2);
//方式3:直接使用Integer类的静态功能:public static String toString(int i)
String result3 = Integer.toString(a);
System.out.println(result3);
String转为int,
//将String--->int: String必须为数字字符串
String str = "200" ;
//方式1:使用Integer的构造方法
Integer ii = new Integer(str) ;//Integer--->int
int number = ii.intValue();//public int intValue()
System.out.println(number);
//方式2: String---Integer----int
//public static Integer valueOf(String s)
Integer ii2 = Integer.valueOf(str);
int number2 = ii2.intValue();
System.out.println(number2);
//常用:方式3 经常使用
//public static int parseInt(String s)
int number3 = Integer.parseInt(str);
System.out.println(number3);
java.util.Random:随机数生成器
空参构造:通过这个构造:调用nextInt(): 获取int类型的范围内的随机数
调用nextInt(int n):0-n之间随机数
每一次产生的随机不相同!
Random(long seed):
创建一个随机数生成器: 传递seed(初始种子)
调用nextInt(): 获取int类型的范围内的随机数
调用nextInt(int n):0-n之间随机数
产生随机相同
//无参构造:每次产生随机不相同
Random random = new Random() ;
for(int x = 0 ;x < 10 ; x ++){//加入循环,输出10次随机数
int number = random.nextInt(30) +1; //0-n之间随机数:不包括n
System.out.println(number);
}
日历类
不能new ,所以提供了一个静态功能,返回值是当前类本身!
public static Calendar getInstance() :通过底层它的子类创建该类实例 (常用的功能)
public int get(int field):获取相关的日历信息:参数为相关的日历字段
public static final int YEAR:年份
public static final int MONTH:月份(1月份从角标0开始,0-11)
public static final int DATE:月中的某一天
int year = calendar.get(Calendar.YEAR) ;
int month = calendar.get(Calendar.MONTH) ;
int date = calendar.get(Calendar.DATE) ;
System.out.println("当前日期是:"+year+"-"+(month+1)+"-"+date);
为某个字段添加或者减去时间量
public abstract void add(int field,int amount): 为某个字段添加或者减去时间量
//public static final int YEAR:年份
//public static final int MONTH:月份(1月份从角标0开始,0-11)
//public static final int DATE:月中的某一天
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR) ;//获取年
int month = calendar.get(Calendar.MONTH) ;//获取月
int date = calendar.get(Calendar.DATE) ;//获取日
System.out.println(year+"-"+(month+1)+"-"+date);//获取当前年月日信息2021-5-20
//给年份设置时间量
calendar.add(Calendar.YEAR,5);//5年后的10天前
year = calendar.get(Calendar.YEAR) ;
alendar.add(Calendar.DATE,-10);
date = calendar.get(Calendar.DATE) ;
System.out.println(year+"-"+(month+1)+"-"+date);//2026-5-10
//public final void set(int year,
// int month,
// int date)
calendar.set(2018,3,20);
year = calendar.get(Calendar.YEAR) ;
month = calendar.get(Calendar.MONTH) ;
System.out.println(year+"-"+(month+1)+"-"+date);//2018-4-20
中小数精确计算的类
构造方法: public BigDecimal(String val)
字段: public static final int ROUND_HALF_UP:舍入模式:四舍五入
成员方法:
public BigDecimal add(BigDecimal augend) :加法运算
public BigDecimal add(BigDecimal augend):减法
public BigDecimal multiply(BigDecimal multiplicand):乘法
public BigDecimal divide(BigDecimal divisor):除法
//创建一个BigDecimal对象
BigDecimal bg1 = new BigDecimal("1.01") ;
BigDecimal bg2 = new BigDecimal("0.36") ;
System.out.println(bg1.divide(bg2,3, RoundingMode.HALF_UP))//输出精确值,保留小数点后三位2.806
Date
java.util.Date类 :表示特定的瞬间,精确到毫秒
构造方法:
public Date():表示当前系统分配的系统时间(精确到毫秒)
public Date(long date):将long----Date日期格式
与1970年1月1日 0:0:0 GMT(格林威治时间)
第一个构造方法---获取当前系统时间!
//创建一个Date类对象
Date date = new Date() ;
System.out.println(date);//Date格式//输出当前系统时间,格式:Thu May 20 10:41:45 CST 2021
日期和String文本的相互转换的工具类
public long getTime() ;获取时间毫秒数(返回值来自:1970年1月1日)
Date date = new Date() ; 获取当前系统时间:Date日期格式
SimpleDateFormat如何使用
构造方法:
public SimpleDateFormat(String pattern)
yyyy:表示年
MM:月
dd:月中的日期
HH:时
mm:分钟
ss:秒
public String format(Date date) :格式化
public Date parse(String source) throws ParseException{}
//构造方法私有化
private 类名(){}
//提供静态功能
//将Date--->String 格式化
public static String date2String(Date date,String pattern){
//创建SimpleDateFormat对象
//SimpleDateFormat sdf = new SimpleDateFormat(pattern) ;
//String source = sdf.format(date);
//return source ;
return new SimpleDateFormat(pattern).format(date) ;
}
//将String--->Date日期格式
public static Date string2Date(String source,String pattern) throws ParseException {
//分步走
//SimpleDateFormat sdf = new SimpleDateFormat(pattern) ;
//Date date = sdf.parse(source);
//return date ;
return new SimpleDateFormat(pattern).parse(source) ;
public static void main(String[] args) throws ParseException {
//Date日期格式----->文本:String :格式化
Date date = new Date() ;
System.out.println(date); //Thu May 20 11:01:39 CST 2021
//描述 "2021-5-20"
// public SimpleDateFormat(String pattern)
//创建SimpleDateFormat对象
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd") ;
//public String format(Date date) :格式化
String strDate = sdf.format(date);
System.out.println(strDate);
System.out.println("-----------------------------------------");
//String文本日期格式---->Date日期格式 : 解析过程
//public SimpleDateFormat(String pattern)
//注意:SimpleDateFormat的模式必须和String当前日期文本的格式一致
String source = "2022-5-20" ;
//创建SimpleDateFormart对象
//SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日") ;
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd") ;
//public Date parse(String source) throws ParseException{}
Date date2 = sdf2.parse(source) ;
System.out.println(date2);
测试DateUtils的两个功能
Date date = new Date() ;
String strDate = DateUtils.date2String(date, "yyyy-MM-dd");
System.out.println(strDate);//输出本地时间"2021-05-20"
String s = "2008-5-12" ;
Date date2 = DateUtils.string2Date(s, "yyyy-MM-dd");
System.out.println(date2);//输出2008年5月12日,Mon May 12 00:00:00 CST 2008
Math类:abs求绝对值
Jdk5新特性:静态导入:导入到方法的级别,前提条件是方法必须静态
注意:自定义的方法名不能和被导入的静态方法名冲突,否则报错!
int max = Math.max(10, 20);
System.out.println(max);//求最大值,输出20
int num = Math.abs(-100);
System.out.println(num);
int number = java.lang.Math.abs(-100); //区分abs方法,求绝对值,输出100
System.out.println(number);
final,finally,finalize的区别?
面试题
final,finally,finalize的区别?
final:状态修饰符(最终,无法更改的)
修饰类,类不能被继承
修饰方法,方法不能重写
修饰变量,变量是一个常量
finalize是一个方法,是Object类的成员方法:
当前垃圾回收器开启的时候,回收内存中没有更多引用对象, 自动回收这些对象,以便节省被占用的内存空间!
java.lang.System:System 类包含一些有用的类字段和方法。它不能被实例化。
常用的两个字段
public static final InputStream int ; 标准输入流
public static final PrintStream out ; 标准输出流
public static final PrintStream err ; 标准错误输出流
常用方法:
public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)
public static void exit(int status):参数为0:正常终止jvm
public static void gc():手动开启垃圾回收器,开启垃圾回收器,回收内存中没有更多引用的对象,节省当前对象所占用的空间
public static long currentTimeMillis():获取时间相关的毫秒数 (很少单独使用:计算一个程序的执行效率!)
Student s = new Student("张三",21) ;
System.out.println(s) ;
s = null ; //空对象:没有更多引用了
System.gc() ;//手动开启垃圾回收器---->调用finalize()回收不用的对象(GC)
System.out.println("程序开始了");
System.exit(0);//终止jvm----->main方法也就结束了...
System.out.println("程序结束了");//不输出,,因为上一句结束了Java虚拟机
数组的复制
public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)
复制数组操作:
参数1:原数组,
参数2:从原数组的某个位置开始
参数3:目标数组
参数4:目标数组的目标位置
参数5:复制的长度
int[] arr1 = {11,22,33,44,55} ;
int[] arr2 = {1,2,3,4,5,6,7,8,9} ;
System.out.println("复制之前:");
//Arrays的toString(数组)
System.out.println(Arrays.toString(arr1));//输出[11, 22, 33, 44, 55]
System.out.println(Arrays.toString(arr2));//输出[1, 2, 3, 4, 5, 6, 7, 8, 9]
System.arraycopy(arr1,2,arr2,4,3);//将arr1的索引值为2的值替换到arr2,arr2从索引值4开始替换,长度为3
System.out.println(Arrays.toString(arr1));//输出[11, 22, 33, 44, 55]
System.out.println(Arrays.toString(arr2));//输出[1, 2, 3, 4, 33, 44, 55, 8, 9]
集合和数组的区别?
1)长度的区别
集合:支持可变的长度
数组:长度是固定的
2)存储数据类型的区别
集合:只能存储引用数据类型
数组:既可以存基本数据类型,也可以存储引用数据类型;
3)存储元素的区别
集合:集合中存储的元素:可以是任意引用类型元素
举例:
白酒参着啤酒红酒可乐
数组:存储的元素:只能是同一个类型元素!
举例: 水杯中的水
基本功能:
添加元素
boolean add(Object e)
删除元素
void clear():暴力删除,全部清空
boolean remove(Object o):删除指定的元素
判断功能
判断集合中是否包含元素
boolean contains(Object o):判斷集合是否包含指定的元素
boolean isEmpty():判断集合是否为空
获取集合的元素数:
int size()
转换功能:
Object[] toArray():将集合转换成数组
//创建一个集合Collection对象
Collection collection = new ArrayList() ;
//添加元素
//boolean add(Object e)
collection.add("hello") ;
collection.add("world") ;
collection.add("javaEE") ;
System.out.println(collection);//输出[hello, world, javaEE]
System.out.println(collection.remove("javaEE")) ;//删除("javaEE"),删除成功输出true
System.out.println(collection);//输出[hello, world]
// collection.clear();//暴力删除
System.out.println(collection);
// boolean contains(Object o):判斷集合是否包含指定的元素
System.out.println(collection.contains("hello"));//包含则为true
System.out.println(collection.contains("android"));//不包含则为false
System.out.println(collection.size());//获取集合的元素数,两组输出2
System.out.println(collection.isEmpty());//判断集合是否为空,非空则为false
###
Day5
Collection集合的高级功能:
//boolean addAll(Collection c):添加一个集合中的所有元素
//boolean removeAll(Collection c):删除集合的所有元素
//boolean containsAll(Collection c) :判断是否包含所有元素,包含所有元素才返回true
boolean retainAll(Collection c):
//System.out.println(c1.addAll(c2));//将c2中的元素全部添加到c1中
//System.out.println(c1.removeAll(c2));//删除c1中包含c2的元素,
例c1中有{a1,a2,a3},c2中有{a2,a3}a2,a3是相同的,删除a2,a3,返回true
//System.out.println(c1.containsAll(c2));,
例如:c1中有{a1,a2,a3},c2中有{a2,a3},返回true,只能c1比c2多,或者包含全部返回true,
//System.out.println(c1.retainAll(c2));//判断c1跟c2的交集,只能c1包含c2才返回true,相同不行
集合专有迭代器:Iterator iterator() :Collection接口的迭代器
迭代器属于集合的专有遍历方式
Iterator:接口
Object next()返回迭代的下一个元素。
boolean hasNext():判断迭代器中是否存在下一个元素
Collection c = new ArrayList() ;
//添加元素
c.add("hello") ;
c.add("world") ;
c.add("javaee") ;
Iterator it = c.iterator();//使用Collection集合的迭代器遍历
while(it.hasNext()){ //循环改进:while循环
Object next = it.next(); //存储的元素 new String("hello") "hello"
String s = (String) next;//向下转型
System.out.println(s+"---"+s.length());//遍历同时获取子串长度
给集合中添加一些字符串元素
ava.util.ConcurrentModificationException:并发修改异常
出现这个异常: 使用Iterator迭代器去遍历元素,不能使用集合操作元素
解决方案:
1)要么就是集合遍历,集合添加
2)要么迭代器去遍历元素,迭代器去添加元素
1迭代器去遍历元素,迭代器去添加元素
List list = new ArrayList() ;
list.add("hello") ;
list.add("world") ;
list.add("android") ;
ListIterator lit = list.listIterator() ;
while(lit.hasNext()){
Object obj = lit.next();
String s = (String) obj;
if("world".equals(s)){
//添加元素
//迭代器添加
lit.add("javaee") ;
}
}
//遍历集合
// Iterator it2 = c.iterator();
ListIterator lit2 = list.listIterator();
while(lit2.hasNext()){
Object obj = lit2.next() ;
System.out.println(obj);
}
2集合遍历,集合添加
//创建一个集合对象
//Collection c = new ArrayList() ;不使用Collection,因为Collection是List的父类,创建Collection的对象 List接口的特有方法不能使用
List list = new ArrayList() ;
//添加元素
list.add("hello") ;
list.add("world") ;
list.add("android") ;
//集合遍历集合添加
for(int x = 0 ; x < list.size() ; x ++){
String s = (String) list.get(x);
if(s.equals("world")){
list.add("javaee") ;//添加元素
}
}
Iterator iterator = list.iterator();
while(iterator.hasNext()){
String s = (String) (iterator.next());
System.out.println(s);
泛型
为了让我们集合的元素类型一致,所以Java提供了泛型,
模拟数组方式,在创建集合对象的时候,就已经明确了类型,防止出现安全问题!
格式:
集合<存储类型> 对象名 =new 子实现类名<存储类型>() ;
泛型的好处:
1)提供程序的安全性,避免了强制类型转换
2)将运行时期异常提前了编译时期
3)解决创建集合的黄色警告线问题
泛型应用范围:---->集合中使用居多! Class:反射中
泛型可以在接口上,也可以定义在类上,也可以在方法上使用!
//@SuppressWarnings("all"):jdk内置注解: 压制警告 注解(接口)
Collection<String> c = new ArrayList<String>() ;
c.add("hello") ;
// c.add(100) ;//泛型中只能存储同一元素
c.add("world") ;
c.add("javaee") ;
System.out.println(c);
Iterator<String> it = c.iterator();
while(it.hasNext()){
String s = it.next() ;
System.out.println(s+"---"+s.length());
向下转型时出现类型不匹配异常(ClassCastException)
//创建工具类对象
ObjectTool objectTool = new ObjectTool() ;
objectTool.set("张三"); //Object obj = new String ("") ;
//获取它的内容
String s = (String) objectTool.get();
System.out.println("姓名是:"+s);
//java.lang.ClassCastException:
// Integer i = (Integer) objectTool.get();
//System.out.println(i);//写程序时不会报错,编译时会出现java.lang.ClassCastException:类型不匹配
因为上面输入的是String类型,
将泛型定义在类上
早期没有使用泛型之前,程序不安全
多态: 向下转型----->出现类型不匹配,存储的类型和接收的类中不一致(ClassCastException)
现在将泛型定义在类上:
可以提高程序安全性,避免了强制类型转换,将运行时期异常提前了编译时期
public class ObjectTool<T> {
private T obj ;
//定义设置数据的方法
public void set(T obj){
this.obj = obj ;
}
//定义一个获取数据的方法
public T get(){
return obj ;
}
}
------------------------------
//创建ObjectTool<>对象:明确了类型
ObjectTool<String> ot = new ObjectTool<String>() ;
ot.set("张三");
//Integer i = ot.get() ;
String i = ot.get() ;
System.out.println("姓名是:"+i);
ObjectTool<Integer> ot2 = new ObjectTool<Integer>() ;
ot2.set(41);
Integer ii = ot2.get();
System.out.println("年龄是:"+ii);
将泛型定义在方法上,可以传递任何数据类型,保证方法扩展性
public class ObjectTool {
public <T> void show(T t){ //提供这个方法的扩展性,形式参数可以是任意的类型:Object
System.out.println(t);
}
---------------------
main
ObjectTool ot = new ObjectTool() ;
ot.show(100);
ot.show(true);
ot.show("hello");
ot.show('A');
泛型的高级通配符
泛型高级通配符
<?> :这个集合可以存储任意的Java数据类型 或者是Object
<? extends E>:向下限定: 当前是E这个类型或者是E类型的子类 (从后往前看符号)
<? super E>:向上限定:跟E这个类类型一致或者是它的父类
//Collection<? extends Animal> c6 = new ArrayList<Object>() ;创建集合时,泛型前后要保持一致
//创建集合对象
Collection<?> c1 = new ArrayList<Object>() ;
Collection<?> c2 = new ArrayList<Animal>() ;
Collection<?> c3 = new ArrayList<Cat>() ;
Collection<?> c4 = new ArrayList<Dog>() ;
Collection<? extends Animal> c5 = new ArrayList<Animal>() ;
//Collection<? extends Animal> c6 = new ArrayList<Object>() ;创建集合时,泛型前后要保持一致
Collection<? extends Animal> c6 = new ArrayList<Cat>() ;
Collection<? extends Animal> c7 = new ArrayList<Dog>() ;
Collection<? super Cat> c8 = new ArrayList<Cat>() ;
Collection<? super Cat> c9 = new ArrayList<Animal>() ;
Collection<? super Cat> c10 = new ArrayList<Object>() ;
}
}
class Animal{
}
class Dog extends Animal{}
class Cat extends Animal{}
List
List的三个子实现的特点:
{11,22,33,44,55}
ArrayList
List 接口的大小可变数组的实现:底层数据结构是数组
数组--->查询元素 数组名称[角标]
查询快,增删慢
线程角度:
是一个不安全的类,不同步的,所以默认没有明确要求使用哪种集合都是使用ArrayList(执行效率高)
Vector
可以实现可增长的对象数组; 底层数据结构数组
数组--->查询元素 数组名称[角标]
查询快,增删慢
线程角度:
Vector 是同步的,所以线程安全可靠, 执行效率低
LinkedList
链接列表实现:底层数据结构是链表
查询慢:都需要从链接列表查到末尾
增删快:数据域和指针域; 使用中间互换!
线程角度:
实现不同步的,是一个线程不安全的类,执行效率高!
List特有功能
List集合特点:
有序的(存储和取出一致)(先存谁,先取谁)
集合的元素是可以重复的
特有功能
void add(int index,Object element):在指定的位置处 添加元素
Object get(int index):通过角标可以获取指定的元素 + size() :普通for循环遍历
ListIterator<Object> listIterator(): 可以使用List集合的专有遍历方式 Object remove(int index):通过该角标删除指定的元素
List集合遍历方式
Object[] toArray()
Collection的迭代器:Iterator iterator()
size()+get()相结合
List<String> list = new ArrayList<String>() ;//添加元素
list.add("hello") ;
list.add("world") ;
list.add("world") ;
list.add("javaee") ;
list.add("javaee") ;
System.out.println(list);
list.add(2,"android") ;//在角标2的位置添加"android",此时"android"角标为2
System.out.println(list);
String s = list.get(4);//获取指定角标的元素
System.out.println(s);
list.add(2,"android") ;//在指定位置添加元素
System.out.println(list);
System.out.println(list.remove(2)); //删除指定索引的元素,输出被删除的元素
System.out.println(list);
逆向遍历,需要先正向遍历,不然没有意义,输出空的
List去重的方法
之前:List<String>因为String底层重写了equals方法,所以比较的是内容是否相同
contains方法底层依赖于equals方法,所以底层判断的是用==,判断的是地址值
List<Student> list = new ArrayList<Student>() ;
//创建一些学生
Student s1 = new Student("张三",41) ;
Student s2 = new Student("张三",41) ;
Student s3 = new Student("张三",35) ;
Student s4 = new Student("文章",30) ;
Student s5 = new Student("马宝国",25) ;
Student s6 = new Student("王宝强",35) ;
Student s7 = new Student("文章",30) ;
list.add(s1) ;
list.add(s2) ;
list.add(s3) ;
list.add(s4) ;
list.add(s5) ;
list.add(s6) ;
list.add(s7) ;
//新建一个集合
List<Student> newList = new ArrayList<Student>() ;
//遍历以前的集合
Iterator<Student> it = list.iterator();
while(it.hasNext()){
Student student = it.next();
if(!newList.contains(student)) {
newList.add(student) ;
}
}
//遍历新集合
Iterator<Student> it2 = newList.iterator();
while(it2.hasNext()){
Student s = it2.next() ;
System.out.println(s.getName()+"---"+s.getAge());
}
}
此时将学生信息全部打印(不会去除重复的信息)
如果需要去除重复的信息就必须在当前类中重写equals以及 hashCode()
1)利用重写equals以及 hashCode()去重
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
if (age != student.age) return false;
return name != null ? name.equals(student.name) : student.name == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
return result;
}
2)选择排序去除
利用选择排序思想
使用0角标对应的元素和后面的元素进行比较,如果后面的元素重复了,将后面定义的去除,角标自减(--)
而且使用集合删除元素!
for(int x = 0 ; x < list.size()-1 ; x ++){//比较次数
for(int y = x + 1 ; y< list.size() ; y ++){
if(list.get(y).equals(list.get(x))){
//先删除后面的元素
list.remove(y) ;
y-- ;
}
}
}
//迭代器
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){
String s = iterator.next() ;
System.out.println(s);
}