Day10
引用類型作為方法的形參
類名:(匿名對象的時候其實我們已經(jīng)講過了)需要的是該類的對象
抽象類:需要的是該抽象的類子類對象
接口:需要的是該接口的實現(xiàn)類對象
//類名作為方法的形式參數(shù)
class Student {
public void study() {
System.out.println("Good Good Study,Day Day Up");
}
}
class StudentDemo {
public void method(Student s) { //ss; ss = new Student(); Student s = new Student();
s.study();
}
}
class StudentTest {
public static void main(String[] args) {
//需求:我要測試Student類的study()方法
Student s = new Student(); //創(chuàng)建對象
s.study(); //調(diào)用方法
System.out.println("----------------");
//需求2:我要測試StudentDemo類中的method()方法
StudentDemo sd = new StudentDemo();
Student ss = new Student();
sd.method(ss);
System.out.println("----------------");
//匿名對象用法
new StudentDemo().method(new Student());
}
}
//抽象類作為方法的形式參數(shù)
abstract class Person {
public abstract void study();
}
class PersonDemo {
public void method(Person p) {//p; p = new Student(); Person p = new Student(); //多態(tài)
p.study();
}
}
//定義一個具體的學(xué)生類
//抽象類作為方法的形式參數(shù)
class Student extends Person {
public void study() {
System.out.println("Good Good Study,Day Day Up");
}
}
class PersonTest {
public static void main(String[] args) {
//目前是沒有辦法的使用的
//因為抽象類沒有對應(yīng)的具體類
//那么淋样,我們就應(yīng)該先定義一個具體類
//需求:我要使用PersonDemo類中的method()方法
PersonDemo pd = new PersonDemo();
Person p = new Student();
pd.method(p);
}
}
//接口作為方法的形式參數(shù)
interface Love {
public abstract void love();
}
class LoveDemo {
public void method(Love l) { //l; l = new Teacher(); Love l = new Teacher(); 多態(tài)
l.love();
}
}
//定義具體類實現(xiàn)接口
class Teacher implements Love {
public void love() {
System.out.println("老師愛學(xué)生,愛Java");
}
}
class TeacherTest {
public static void main(String[] args) {
//需求:我要測試LoveDemo類中的love()方法
LoveDemo ld = new LoveDemo();
Love l = new Teacher();
ld.method(l);
}
}
引用類型作為返回值
類:返回的是該類的對象
抽象類:返回的是該抽象類的子類對象
接口:返回的是該接口的實現(xiàn)類的對象
//類最為返回值
class Student {
public void study() {
System.out.println("Good Good Study,Day Day Up");
}
}
class StudentDemo {
public Student getStudent() {
//Student s = new Student();
//Student ss = s;
//Student s = new Student();
//return s;
return new Student();
}
}
class StudentTest2 {
public static void main(String[] args) {
//需求:我要使用Student類中的study()方法
//但是檬贰,這一次我的要求是病线,不要直接創(chuàng)建Student的對象
//讓你使用StudentDemo幫你創(chuàng)建對象
StudentDemo sd = new StudentDemo();
Student s = sd.getStudent(); //new Student(); Student s = new Student();
s.study();
}
}
//抽象類作為返回值
abstract class Person {
public abstract void study();
}
class PersonDemo {
public Person getPerson() {
//Person p = new Student();
//return p;
return new Student();
}
}
class Student extends Person {
public void study() {
System.out.println("Good Good Study,Day Day Up");
}
}
class PersonTest2 {
public static void main(String[] args) {
//需求:我要測試Person類中的study()方法
PersonDemo pd = new PersonDemo();
Person p = pd.getPerson(); //new Student(); Person p = new Student(); 多態(tài)
p.study();
}
}
//接口作為返回值
interface Love {
public abstract void love();
}
class LoveDemo {
public Love getLove() {
//Love l = new Teacher();
//return l;
return new Teacher();
}
}
//定義具體類實現(xiàn)接口
class Teacher implements Love {
public void love() {
System.out.println("老師愛學(xué)生,愛Java");
}
}
class TeacherTest2 {
public static void main(String[] args) {
//如何測試呢?
LoveDemo ld = new LoveDemo();
Love l = ld.getLove(); //new Teacher(); Love l = new Teacher(); 多態(tài)
l.love();
}
}
鏈?zhǔn)骄幊?/strong>
每次調(diào)用完畢后返回的是一個對象(只有對象才能繼續(xù)調(diào)方法)
class Student {
public void study() {
System.out.println("Good Good Study,Day Day Up");
}
}
class StudentDemo {
public Student getStudent() {
return new Student();
}
}
class StudentTest3 {
public static void main(String[] args) {
//如何調(diào)用的呢?
StudentDemo sd = new StudentDemo();
//Student s = sd.getStudent();
//s.study();
//相當(dāng)于下邊的
sd.getStudent().study();
}
}
包
其實就是文件夾
作用
把相同的類名放到不同的包中
對類進行分類管理
舉例:
學(xué)生:增加,刪除缩赛,修改,查詢
老師:增加寒波,刪除吹害,修改,查詢
...
方案1:按照功能分
cn.itcast.add
AddStudent
AddTeacher
cn.itcast.delete
DeleteStudent
DeleteTeacher
cn.itcast.update
UpdateStudent
UpdateTeacher
cn.itcast.find
FindStudent
FindTeacher
方案2:按照模塊分
cn.itcast.teacher
AddTeacher
DeleteTeacher
UpdateTeacher
FindTeacher
cn.itcast.student
AddStudent
DeleteStudent
UpdateStudent
FindStudent
包的定義
package 包名;
多級包用.分開即可
注意事項:
package語句必須是程序的第一條可執(zhí)行的代碼
package語句在一個java文件中只能有一個
如果沒有package亿虽,默認(rèn)表示無包名
帶包的編譯和運行:
手動式
編寫一個帶包的java文件
通過javac命令編譯該java文件
手動創(chuàng)建包名
把b步驟的class文件放到c步驟的最底層包
回到和包根目錄在同一目錄的地方菱涤,然后運行
帶包運行
自動式
編寫一個帶包的java文件
javac編譯的時候帶上-d即可
javac -d . HelloWorld.java
回到和包根目錄在同一目錄的地方,然后運行
帶包運行
導(dǎo)包
格式:import 包名;
這種方式導(dǎo)入是到類的名稱,注意:我們用誰就導(dǎo)誰
例:import cn.itcast.Demo //Demo為類名
package,import,class的順序關(guān)系
package > import > class
Package:只能有一個
import:可以有多個
class:可以有多個洛勉,以后建議是一個
權(quán)限修飾符的訪問
本類 同一個包下(子類和無關(guān)類) 不同包下(子類) 不同包下(無關(guān)類)
private Y
默認(rèn) Y Y
protected Y Y Y
public Y Y Y Y
protected 受保護的粘秆,一般給子類使用
修飾符的分類
權(quán)限修飾符:private,默認(rèn)的收毫,protected攻走,public
狀態(tài)修飾符:static殷勘,final
抽象修飾符:abstract
類可以用的修飾符
權(quán)限修飾符:默認(rèn)修飾符,public
狀態(tài)修飾符:final
抽象修飾符:abstract
用的最多的就是:public
成員變量可以用的修飾符
權(quán)限修飾符:private昔搂,默認(rèn)的玲销,protected,public
狀態(tài)修飾符:static摘符,final
用的最多的就是:private
構(gòu)造方法可以用的修飾符
權(quán)限修飾符:private贤斜,默認(rèn)的,protected逛裤,public
用的最多的就是:public
成員方法可以用的修飾符
權(quán)限修飾符:private瘩绒,默認(rèn)的,protected别凹,public
狀態(tài)修飾符:static草讶,final
抽象修飾符:abstract
用的最多的就是:public
除此以外的組合規(guī)則:
成員變量:public static final
成員方法:public static
public abstract
public final
內(nèi)部類
把類定義在其他類的內(nèi)部,這個類就被稱為內(nèi)部類
舉例:在類A中定義了一個類B炉菲,類B就是內(nèi)部類
內(nèi)部的訪問特點
內(nèi)部類可以直接訪問外部類的成員堕战,包括私有
外部類要訪問內(nèi)部類的成員,必須創(chuàng)建對象
內(nèi)部類的位置
在成員位置(變量處)稱為成員內(nèi)部類
在局部位置(方法體內(nèi))稱為局部內(nèi)部類
成員內(nèi)部類的直接訪問
格式: 外部類.內(nèi)部類 對象名 = 外部類對象.內(nèi)部類對象
例: Out.In oi = new Out().In;
成員內(nèi)部類的修飾符
private 為了保證數(shù)據(jù)的安全性
static 為了方便訪問數(shù)據(jù)
注意:靜態(tài)內(nèi)部類訪問的外部類數(shù)據(jù)必須用靜態(tài)修飾
成員內(nèi)部類被靜態(tài)修飾后的訪問方式是
格式:外部類名.內(nèi)部類名 對象名 = new 外部類名.內(nèi)部類名();
/*案例:我有一個人(人有身體拍霜,身體內(nèi)有心臟)
class Body {
private class Heart {
public void operator() {
System.out.println("心臟搭橋");
}
}
public void method() {
if(如果你是外科醫(yī)生) {
Heart h = new Heart();
h.operator();
}
}
}
按照我們剛才的講解嘱丢,來使用一下
Body.Heart bh = new Body().new Heart();
bh.operator();
//加了private后,就不能被訪問了
Body b = new Body();
b.method();
*/
class Outer {
private int num = 10;
private static int num2 = 100;
//內(nèi)部類用靜態(tài)修飾是因為內(nèi)部類可以看出是外部類的成員
public static class Inner {
public void show() {
//System.out.println(num);
System.out.println(num2);
}
public static void show2() {
//System.out.println(num);
System.out.println(num2);
}
}
}
class InnerClassDemo4 {
public static void main(String[] args) {
//使用內(nèi)部類
// 限定的新靜態(tài)類
//Outer.Inner oi = new Outer().new Inner();
//oi.show();
//oi.show2();
//成員內(nèi)部類被靜態(tài)修飾后的訪問方式是:
//格式:外部類名.內(nèi)部類名 對象名 = new 外部類名.內(nèi)部類名();
Outer.Inner oi = new Outer.Inner();
oi.show();
oi.show2();
//show2()的另一種調(diào)用方式,靜態(tài)方法和靜態(tài)成員可以通過類名來訪問
Outer.Inner.show2();
}
}
/*面試題:
在三個輸出語句中填空分別輸出30祠饺,20越驻,10
注意:
1:內(nèi)部類和外部類沒有繼承關(guān)系
2:通過外部類名限定this對象
Outer.this
*/
class Outer {
public int num = 10;
class Inner {
public int num = 20;
public void show() {
int num = 30;
System.out.println(num); //就近原則,輸出30
System.out.println(this.num); //當(dāng)前類的num,及Inner的num,輸出20
//System.out.println(new Outer().num);通過對象調(diào)用成員變量,可以輸出10
System.out.println(Outer.this.num); //通過類名限制this,輸出10
}
}
}
class InnerClassTest {
public static void main(String[] args) {
Outer.Inner oi = new Outer().new Inner(); //創(chuàng)建成員內(nèi)部對象
oi.show();
}
}
局部內(nèi)部類
可以直接訪問外部類的成員
在局部位置,可以創(chuàng)建內(nèi)部類對象道偷,通過對象調(diào)用內(nèi)部類方法缀旁,來使用局部內(nèi)部類功能
/*面試題:
局部內(nèi)部類訪問局部變量的注意事項?
A:局部內(nèi)部類訪問局部變量必須用final修飾
B:為什么呢?
局部變量是隨著方法的調(diào)用而調(diào)用,隨著調(diào)用完畢而消失勺鸦。
而堆內(nèi)存的內(nèi)容并不會立即消失并巍。所以,我們加final修飾换途。
加入final修飾后懊渡,這個變量就成了常量。既然是常量军拟。你消失了剃执。
我在內(nèi)存中存儲的是數(shù)據(jù)20,所以懈息,我還是有數(shù)據(jù)在使用肾档。
*/
class Outer {
private int num = 10;
public void method() {
//int num2 = 20;
//final int num2 = 20;
class Inner {
public void show() {
System.out.println(num);
//從內(nèi)部類中訪問本地變量num2; 需要被聲明為最終類型
System.out.println(num2);//20
}
}
//System.out.println(num2);
Inner i = new Inner();
i.show();
}
}
class InnerClassDemo5 {
public static void main(String[] args) {
Outer o = new Outer();
o.method();
}
}
匿名內(nèi)部類
就是內(nèi)部類的簡化寫法
前提:存在一個類或者接口
這里的類可以是具體類也可以是抽象類
格式:
new 類名或者接口名(){
重寫方法;
}
匿名內(nèi)部類本質(zhì)是一個繼承了該類或者實現(xiàn)了該接口的子類匿名對象
interface Inter {
public abstract void show();
public abstract void show2();
}
class Outer {
public void method() {
//一個方法的時候
/*
new Inter() {
public void show() {
System.out.println("show");
}
}.show();
*/
//二個方法的時候
/*
new Inter() {
public void show() {
System.out.println("show");
}
public void show2() {
System.out.println("show2");
}
}.show();
new Inter() {
public void show() {
System.out.println("show");
}
public void show2() {
System.out.println("show2");
}
}.show2();
*/
//如果我是很多個方法,就很麻煩了
//那么,我們有沒有改進的方案呢?
Inter i = new Inter() { //多態(tài)
public void show() {
System.out.println("show");
}
public void show2() {
System.out.println("show2");
}
};
i.show();
i.show2();
}
}
class InnerClassDemo6 {
public static void main(String[] args) {
Outer o = new Outer();
o.method();
}
}
/*
匿名內(nèi)部類面試題:
按照要求怒见,補齊代碼
interface Inter { void show(); }
class Outer { //補齊代碼 }
class OuterDemo {
public static void main(String[] args) {
Outer.method().show();
}
}
要求在控制臺輸出”HelloWorld”
*/
interface Inter {
void show();
//public abstract
}
class Outer {
//補齊代碼
public static Inter method() {
//子類對象 -- 子類匿名對象
return new Inter() {
public void show() {
System.out.println("HelloWorld");
}
};
}
}
class OuterDemo {
public static void main(String[] args) {
Outer.method().show();
/*
1:Outer.method()可以看出method()應(yīng)該是Outer中的一個靜態(tài)方法戒祠。
2:Outer.method().show()可以看出method()方法的返回值是一個對象。
又由于接口Inter中有一個show()方法,所以我認(rèn)為method()方法的返回值類型是一個接口速种。
*/
}
}
匿名對象在開發(fā)中的使用
/*
匿名內(nèi)部類在開發(fā)中的使用
*/
interface Person {
public abstract void study();
}
class PersonDemo {
//接口名作為形式參數(shù)
//其實這里需要的不是接口姜盈,而是該接口的實現(xiàn)類的對象
public void method(Person p) {
p.study();
}
}
//實現(xiàn)類
class Student implements Person {
public void study() {
System.out.println("好好學(xué)習(xí),天天向上");
}
}
class InnerClassTest2 {
public static void main(String[] args) {
//測試
PersonDemo pd = new PersonDemo();
Person p = new Student();
pd.method(p);
System.out.println("--------------------");
//匿名內(nèi)部類在開發(fā)中的使用
//匿名內(nèi)部類的本質(zhì)是繼承類或者實現(xiàn)了接口的子類匿名對象
pd.method(new Person(){
public void study() {
System.out.println("好好學(xué)習(xí),天天向上");
}
});
}
}
Day11
API
Object類
類 Object 是類層次結(jié)構(gòu)的根類,每個類都使用 Object 作為超類,每個類都直接或者間接的繼承自O(shè)bject類
Object類的方法:
hasnCode()
public int hashCode():返回該對象的哈希碼值
注意:哈希值是根據(jù)哈希算法計算出來的一個值,這個值和地址值有關(guān)配阵,但是不是實際地址值馏颂, 你可以理解為地址值
getName()
返回此 Object 的運行時類Class類的方法
public String getName() 以 String 的形式返回此 Class 對象所表示的實體,就是會輸出調(diào)用對象的包跟類
public class Student extends Object {
}
public class StudentTest {
public static void main(String[] args) {
Student s1 = new Student();
System.out.println(s1.hashCode()); // 11299397
Student s2 = new Student();
System.out.println(s2.hashCode());// 24446859
Student s3 = s1;
System.out.println(s3.hashCode()); // 11299397
System.out.println("-----------");
Student s = new Student();
Class c = s.getClass();
String str = c.getName();
System.out.println(str); // cn.itcast_01.Student
//鏈?zhǔn)骄幊? String str2 = s.getClass().getName();
System.out.println(str2);
}
}
toString()
public String toString() 返回該對象的字符串表示,就是返回該類的所有變量值
使用idea會自動生成重寫
調(diào)用:對象名.toString();
equals
public boolean equals(Object obj) 指示其他某個對象是否與此對象“相等”,默認(rèn)情況下是比較兩個對象的地址值是否相同,使用idea自動生成后可以比較一個類中的兩個對象的具體值是否相同
例:學(xué)生s1和學(xué)生s2的姓名和年齡是否相同
調(diào)用:s1.equals(s2) 比較s1和s2的具體值是否相同
finallize
protected void finalize():當(dāng)垃圾回收器確定不存在對該對象的更多引用時,由對象的垃圾回收器調(diào)用此方法,用于垃圾回收棋傍,但是什么時候回收不確定
Cloneable
此類實現(xiàn)了 Cloneable 接口救拉,以指示 Object.clone() 方法可以合法地對該類實例進行按字段復(fù)制
注意:
要在main方法后加throws CloneNotSupportedException
public static void main(String[] args) throws CloneNotSupportedException {}
還要在類后實現(xiàn)接口Cloneable
public class Student implements Cloneable
**instanceof **
判斷一個對象該類的一個對象
格式:對象名 instranceof 類名
Day12
Scanner
用于接收鍵盤錄入數(shù)據(jù)
使用
-導(dǎo)包
-創(chuàng)建對象
-調(diào)用方法
System類下有一個靜態(tài)的字段:
public static final InputStream in; 標(biāo)準(zhǔn)的輸入流,對應(yīng)著鍵盤錄入
InputStream is = System.in;
構(gòu)造方法:
Scanner(InputStream source)//system.in 就相當(dāng)于InputStram spurce
基本格式:
public boolean hasNextXxx():判斷是否是某種類型的元素
public Xxx nextXxx():獲取該元素
舉例:用int類型的方法舉例
public boolean hasNextInt()
public int nextInt()
注意:InputMismatchException:輸入的和你想要的不匹配
先輸入一個數(shù)值后邊跟一個字符串時會出錯,因為把換行給了字符串
解決方法:
先獲取一個數(shù)值后瘫拣,在創(chuàng)建一個新的鍵盤錄入對象獲取字符串
把所有的數(shù)據(jù)都先按照字符串獲取亿絮,然后要什么,你就對應(yīng)的轉(zhuǎn)換為什么
String
字符串:就是由多個字符組成的一串?dāng)?shù)據(jù),也可以看成是一個字符數(shù)組
通過查看API麸拄,我們可以知道
字符串字面值"abc"也可以看成是一個字符串對象
字符串是常量派昧,一旦被賦值,就不能被改變
構(gòu)造方法:
public String():空構(gòu)造
public String(byte[] bytes):把字節(jié)數(shù)組轉(zhuǎn)成字符串
public String(byte[] bytes,int index,int length):把字節(jié)數(shù)組的一部分轉(zhuǎn)成字符串(從索引index開始,一共length長度)
public String(char[] value):把字符數(shù)組轉(zhuǎn)成字符串
public String(char[] value,int index,int count):把字符數(shù)組的一部分轉(zhuǎn)成字符串
public String(String original):把字符串常量值轉(zhuǎn)成字符串
字符串的方法:
public int length():返回此字符串的長度
//構(gòu)造方法代碼實現(xiàn)
public class StringDemo {
public static void main(String[] args) {
// public String():空構(gòu)造
String s1 = new String();
System.out.println("s1:" + s1);
System.out.println("s1.length():" + s1.length());
System.out.println("--------------------------");
// public String(byte[] bytes):把字節(jié)數(shù)組轉(zhuǎn)成字符串
byte[] bys = { 97, 98, 99, 100, 101 };
String s2 = new String(bys);
System.out.println("s2:" + s2);
System.out.println("s2.length():" + s2.length());
System.out.println("--------------------------");
// public String(byte[] bytes,int index,int length):把字節(jié)數(shù)組的一部分轉(zhuǎn)成字符串
// 我想得到字符串"bcd"
String s3 = new String(bys, 1, 3); //從索引1開始,取三個
System.out.println("s3:" + s3);
System.out.println("s3.length():" + s3.length());
System.out.println("--------------------------");
// public String(char[] value):把字符數(shù)組轉(zhuǎn)成字符串
char[] chs = { 'a', 'b', 'c', 'd', 'e', '愛', '學(xué)', '習(xí)' };
String s4 = new String(chs);
System.out.println("s4:" + s4);
System.out.println("s4.length():" + s4.length());
System.out.println("--------------------------");
// public String(char[] value,int index,int count):把字符數(shù)組的一部分轉(zhuǎn)成字符串
String s5 = new String(chs, 2, 4); //從索引2開始,取4個
System.out.println("s5:" + s5);
System.out.println("s5.length():" + s5.length());
System.out.println("--------------------------");
//public String(String original):把字符串常量值轉(zhuǎn)成字符串
String s6 = new String("abcde");
System.out.println("s6:" + s6);
System.out.println("s6.length():" + s6.length());
System.out.println("--------------------------");
//字符串字面值"abc"也可以看成是一個字符串對象
String s7 = "abcde";
System.out.println("s7:"+s7);
System.out.println("s7.length():"+s7.length());
}
}
字符串的特點:一旦被賦值拢切,就不能改變
public class StringDemo {
public static void main(String[] args) {
String s = "hello";
s += "world";
System.out.println("s:" + s); // helloworld,改變的是s,不是hello,hello在方法區(qū)里邊的值和地址值都沒有改變,拼接生成了一個新的地址值存放
}
}
String s = new String(“hello”)和String s = “hello”;的區(qū)別,前者會創(chuàng)建2個對象蒂萎,后者創(chuàng)建1個對象
==:比較引用類型比較的是地址值是否相同
equals:比較引用類型默認(rèn)也是比較地址值是否相同,而String類重寫了equals()方法淮椰,比較的是內(nèi)容是否相同
public class StringDemo2 {
public static void main(String[] args) {
String s1 = new String("hello");
String s2 = "hello";
System.out.println(s1 == s2);// false
System.out.println(s1.equals(s2));// true
}
}
字符串如果是變量相加五慈,先開空間,在拼接
字符串如果是常量相加主穗,是先加泻拦,然后在常量池找,如果有就直接返回忽媒,否則争拐,就創(chuàng)建
public class StringDemo4 {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "world";
String s3 = "helloworld";
System.out.println(s3 == s1 + s2);// false
System.out.println(s3.equals((s1 + s2)));// true
System.out.println(s3 == "hello" + "world");// false 這個我們錯了,應(yīng)該是true
System.out.println(s3.equals("hello" + "world"));// true
// 通過反編譯看源碼猾浦,我們知道這里已經(jīng)做好了處理陆错。
// System.out.println(s3 == "helloworld");
// System.out.println(s3.equals("helloworld"));
}
}
String類的判斷功能
返回值 方法名 參數(shù)
boolean equals(Object obj):比較字符串的內(nèi)容是否相同,區(qū)分大小寫
boolean equalsIgnoreCase(String str):比較字符串的內(nèi)容是否相同,忽略大小寫
boolean contains(String str):判斷大字符串中是否包含小字符串
boolean startsWith(String str):判斷字符串是否以某個指定的字符串開頭
boolean endsWith(String str):判斷字符串是否以某個指定的字符串結(jié)尾
boolean isEmpty():判斷字符串是否為空
注意:
字符串內(nèi)容為空和字符串對象為空
String s = "";
String s = null;
public class StringDemo {
public static void main(String[] args) {
// 創(chuàng)建字符串對象
String s1 = "helloworld";
String s2 = "helloworld";
String s3 = "HelloWorld";
// boolean equals(Object obj):比較字符串的內(nèi)容是否相同,區(qū)分大小寫
System.out.println("equals:" + s1.equals(s2));
System.out.println("equals:" + s1.equals(s3));
System.out.println("-----------------------");
// boolean equalsIgnoreCase(String str):比較字符串的內(nèi)容是否相同,忽略大小寫
System.out.println("equals:" + s1.equalsIgnoreCase(s2));
System.out.println("equals:" + s1.equalsIgnoreCase(s3));
System.out.println("-----------------------");
// boolean contains(String str):判斷大字符串中是否包含小字符串
System.out.println("contains:" + s1.contains("hello"));
System.out.println("contains:" + s1.contains("hw"));//需要連續(xù)的
System.out.println("-----------------------");
// boolean startsWith(String str):判斷字符串是否以某個指定的字符串開頭
System.out.println("startsWith:" + s1.startsWith("h"));
System.out.println("startsWith:" + s1.startsWith("hello"));
System.out.println("startsWith:" + s1.startsWith("world"));
System.out.println("-----------------------");
//boolean endsWith(String str):判斷字符串是否以某個指定的字符串結(jié)尾
System.out.println("endsWith:"+s1.endsWith("world"));
System.out.println("endsWith:"+s1.endsWith("rld"));
System.out.println("endsWith:"+s1.endsWith("d"));
System.out.println("-----------------------");
// boolean isEmpty():判斷字符串是否為空灯抛。
System.out.println("isEmpty:" + s1.isEmpty());
String s4 = "";
String s5 = null;
System.out.println("isEmpty:" + s4.isEmpty());
// NullPointerException
// System.out.println("isEmpty:" + s5.isEmpty());//s5對象都不存在金赦,所以不能調(diào)用方法,空指針異常
}
}
//小案例,模擬登錄,給三次機會,提示剩余次數(shù),登錄成功后可以開始玩猜數(shù)字小游戲
/*
* 分析:
* A:定義用戶名和密碼
* B:鍵盤錄入用戶名和密碼
* C:比較用戶名和密碼
* 如果都相同对嚼,則登錄成功
* 如果有一個不同夹抗,則登錄失敗
* D:給三次機會,用循環(huán)改進纵竖,最好用for循環(huán)
*/
public class StringDemo {
public static void main(String[] args) {
//系統(tǒng)定義用戶名和密碼
String name = "user1";
String password = "123456";
//用戶輸入用戶名和密碼
for (int i = 0; i < 3; i++) {
Scanner sc = new Scanner(System.in);
System.out.println("請輸入用戶名");
String name2 = sc.nextLine();
System.out.println("請輸入密碼");
String password2 = sc.nextLine();
if ((name.equals(name2)) &&(password.equals(password2))){
System.out.println("登錄成功,開始猜數(shù)字小游戲");
CaiShuZi.start(); //定義了一個類來玩猜數(shù)字
break;
}else if ((2-i) == 0){
System.out.println("密碼鎖定漠烧,請聯(lián)系管理員");
}else {
System.out.println("剩余" + (2 - i) + "次機會");
}
}
}
}
//猜數(shù)字小游戲類
mport java.util.Random;
import java.util.Scanner;
public class CaiShuZi {
private CaiShuZi(){} //屏蔽無參構(gòu)造,不能使用對象來玩游戲
public static void start(){
Random r = new Random();
int num = r.nextInt(10)+1;
while(true){
System.out.println("請輸入1-10之間的數(shù)");
Scanner sc = new Scanner(System.in);
int num1 = sc.nextInt();
if (num1 < num){
System.out.println("猜小了");
}else if (num1 > num){
System.out.println("猜大了");
}else {
System.out.println("猜對了");
break;
}
}
}
}
String類的獲取功能
返回值 方法名 參數(shù)
int length():獲取字符串的長度
char charAt(int index):獲取指定索引位置的字符
int indexOf(int ch):返回指定字符在此字符串中第一次出現(xiàn)處的索引,為什么這里是int類型杏愤,而不是char類型,因為'a'和97其實都可以代表'a'
int indexOf(String str):返回指定字符串在此字符串中第一次出現(xiàn)處的索引
int indexOf(int ch,int fromIndex):返回指定字符在此字符串中從指定位置后第一次出現(xiàn)處的索引
int indexOf(String str,int fromIndex):返回指定字符串在此字符串中從指定位置后第一次出現(xiàn)處的索引
String substring(int start):從指定位置開始截取字符串,默認(rèn)到末尾,包含strat這個位置(包左)
String substring(int start,int end):從指定位置開始到指定位置結(jié)束截取字符串,包含start但不包含end(包左不包右)
public class StringDemo {
public static void main(String[] args) {
// 定義一個字符串對象
String s = "helloworld";
// int length():獲取字符串的長度。
System.out.println("s.length:" + s.length());
System.out.println("----------------------");
// char charAt(int index):獲取指定索引位置的字符
System.out.println("charAt:" + s.charAt(7));
System.out.println("----------------------");
// int indexOf(int ch):返回指定字符在此字符串中第一次出現(xiàn)處的索引
System.out.println("indexOf:" + s.indexOf('l'));
System.out.println("----------------------");
// int indexOf(String str):返回指定字符串在此字符串中第一次出現(xiàn)處的索引
System.out.println("indexOf:" + s.indexOf("owo"));
System.out.println("----------------------");
// int indexOf(int ch,int fromIndex):返回指定字符在此字符串中從指定位置后第一次出現(xiàn)處的索引
System.out.println("indexOf:" + s.indexOf('l', 4));
System.out.println("indexOf:" + s.indexOf('k', 4)); // -1
System.out.println("indexOf:" + s.indexOf('l', 40)); // -1 代表錯誤
System.out.println("----------------------");
// int indexOf(String str,int fromIndex):返回指定字符串在此字符串中從指定位置后第一次出現(xiàn)處的索引
System.out.println("s.indexOf:"+s.indexOf('l',3));
System.out.println("----------------------");
// String substring(int start):從指定位置開始截取字符串,默認(rèn)到末尾已脓。包含start這個索引
System.out.println("substring:" + s.substring(5));
System.out.println("substring:" + s.substring(0));
System.out.println("----------------------");
// String substring(int start,intend):從指定位置開始到指定位置結(jié)束截取字符串,包括start索引但是不包end索引
System.out.println("substring:" + s.substring(3, 8));
System.out.println("substring:" + s.substring(0, s.length()));
}
}
/* 需求:從鍵盤獲取一串字符串,統(tǒng)計該字符串中大寫字母字符,小寫字母字符,數(shù)字字符出現(xiàn)的次數(shù)(不考慮其他字符)
*
*分析:鍵盤錄入
* 遍歷字符,得到每一個字符
* charAt()和length() 結(jié)合得到
* 對大小寫數(shù)字進行計數(shù)
*
**/
public class StringDemo {
public static void main(String[] args) {
//定義三個計數(shù)
int bigCount = 0;
int smallCount = 0;
int numCount = 0;
//創(chuàng)建對象
Scanner sc = new Scanner(System.in);
System.out.println("請輸入一串包含大小寫數(shù)字的字符串");
//獲取鍵盤輸入的賦值給s
String s = sc.nextLine();
for (int i = 0; i < s.length(); i++) {
//獲取字符串的每一個字符
int ch = s.charAt(i);
//進行比較
if ((ch > 'a') && (ch < 'z')){
smallCount++;
}else if ((ch > 'A')&&(ch < 'Z')){
bigCount++;
}else if ((ch > '0')&&(ch < '9')){
numCount++;
}
}
System.out.println("大寫字母有"+ bigCount +"個珊楼,小寫字母有"+ smallCount +"個,數(shù)字有"+ numCount +"個");
}
}
String的轉(zhuǎn)換功能
返回值 方法名 參數(shù)
byte[] getBytes():把字符串轉(zhuǎn)換為字節(jié)數(shù)組,輸出結(jié)果會是對應(yīng)的ascii碼值
char[] toCharArray():把字符串轉(zhuǎn)換為字符數(shù)組
static String valueOf(char[] chs):把字符數(shù)組轉(zhuǎn)成字符串
static String valueOf(int i):把int類型的數(shù)據(jù)轉(zhuǎn)成字符串
注意:String類的valueOf方法可以把任意類型的數(shù)據(jù)轉(zhuǎn)成字符串
String toLowerCase():把字符串轉(zhuǎn)成小寫
String toUpperCase():把字符串轉(zhuǎn)成大寫
String concat(String str):把字符串拼接
public class StringDemo {
public static void main(String[] args) {
// 定義一個字符串對象
String s = "HelloWorld";
// byte[] getBytes():把字符串轉(zhuǎn)換為字節(jié)數(shù)組,輸出結(jié)果會是數(shù)字度液,代表對應(yīng)的ascii碼值
byte[] bys = s.getBytes();
for (int x = 0; x < bys.length; x++) {
System.out.print(bys[x]+" ");
}
System.out.println();
System.out.println("----------------");
// char[] toCharArray():把字符串轉(zhuǎn)換為字符數(shù)組
char[] chs = s.toCharArray();
for (int x = 0; x < chs.length; x++) {
System.out.print(chs[x]+" ");
}
System.out.println();
System.out.println("----------------");
// static String valueOf(char[] chs):把字符數(shù)組轉(zhuǎn)成字符串
String ss = String.valueOf(chs);
System.out.println(ss);
System.out.println("----------------");
// static String valueOf(int i):把int類型的數(shù)據(jù)轉(zhuǎn)成字符串
int i = 100;
String sss = String.valueOf(i);
System.out.println(sss);
System.out.println("----------------");
// String toLowerCase():把字符串轉(zhuǎn)成小寫,但不會改變原字符串
System.out.println("toLowerCase:" + s.toLowerCase());
System.out.println("s:" + s);
System.out.println("----------------");
// String toUpperCase():把字符串轉(zhuǎn)成大寫
System.out.println("toUpperCase:" + s.toUpperCase());
System.out.println("----------------");
// String concat(String str):把字符串拼接
String s1 = "hello";
String s2 = "world";
String s3 = s1 + s2;
String s4 = s1.concat(s2);
System.out.println("s3:"+s3);
System.out.println("s4:"+s4);
}
import java.util.Locale;
import java.util.Scanner;
/*
* 需求:鍵盤輸入一個字符串厕宗,把首字母大寫,其他字母小寫
* 分析:
* 第一步:獲取字符串的第一個位置的字符
* 第二步:獲取字符串其他位置的字符
* 第三步:把第一步獲取的大寫
* 第四步:把第二步獲取的小寫
* 第五步:把第三步第四步拼接
* */
public class StringDemo {
public static void main(String[] args) {
//創(chuàng)建對象
Scanner sc = new Scanner(System.in);
System.out.println("請輸入一個字符串");
String str = sc.nextLine();
//截取字符串
//第一個位置的字符堕担,從0到1已慢,包左不包右
String first = str.substring(0,1);
//從1到末尾
String str1 = str.substring(1);
//變?yōu)榇髮? first = first.toUpperCase(Locale.ROOT);
//變?yōu)樾? str1 = str1.toLowerCase(Locale.ROOT);
//拼接
str = first + str1;
System.out.println(str);
}
}
String類的其他功能
替換功能
String replace(char old,char new),用new替換old
String replace(String old,String new)用new替換old
去除字符串兩空格
String trim()
按字典順序比較兩個字符串
int compareTo(String str),區(qū)分大小寫,按位比較,第一位相同就比較第二位,比較處不同后用前邊的Ascii碼減去后邊的Ascii碼
int compareToIgnoreCase(String str),不去分大小寫,同上
public class StringDemo {
public static void main(String[] args) {
// 替換功能
String s1 = "helloworld";
String s2 = s1.replace('l', 'k');
String s3 = s1.replace("owo", "asdasdasdasd"); //替換不用管是否相同數(shù)量
System.out.println("s1:" + s1);
System.out.println("s2:" + s2);
System.out.println("s3:" + s3);
System.out.println("---------------");
// 去除字符串兩空格
String s4 = " hello world ";
String s5 = s4.trim();
System.out.println("s4:" + s4 + "---");
System.out.println("s5:" + s5 + "---");
// 按字典順序比較兩個字符串
String s6 = "hello";
String s7 = "hello";
String s8 = "abc";
String s9 = "xyz";
System.out.println(s6.compareTo(s7));// 0代表相同
System.out.println(s6.compareTo(s8));// 7代表Ascii碼比s6的小7
System.out.println(s6.compareTo(s9));// -16
}
}
StringBuffer
線程安全的可變字符串
StringBuffer和String的區(qū)別
前者長度和內(nèi)容可變,后者不可變
如果使用前者做字符串的拼接霹购,不會浪費太多的資源
StringBuffer的構(gòu)造方法:
public StringBuffer():無參構(gòu)造方法
public StringBuffer(int capacity):指定容量的字符串緩沖區(qū)對象
public StringBuffer(String str):指定字符串內(nèi)容的字符串緩沖區(qū)對象
StringBuffer的方法:
public int capacity():返回當(dāng)前容量 理論值
public int length():返回長度(字符數(shù)) 實際值
public class StringBufferDemo {
public static void main(String[] args) {
// public StringBuffer():無參構(gòu)造方法
StringBuffer sb = new StringBuffer();
System.out.println("sb:" + sb);
System.out.println("sb.capacity():" + sb.capacity());
System.out.println("sb.length():" + sb.length());
System.out.println("--------------------------");
// public StringBuffer(int capacity):指定容量的字符串緩沖區(qū)對象
StringBuffer sb2 = new StringBuffer(50);
System.out.println("sb2:" + sb2);
System.out.println("sb2.capacity():" + sb2.capacity());
System.out.println("sb2.length():" + sb2.length());
System.out.println("--------------------------");
// public StringBuffer(String str):指定字符串內(nèi)容的字符串緩沖區(qū)對象
StringBuffer sb3 = new StringBuffer("hello");
System.out.println("sb3:" + sb3);
System.out.println("sb3.capacity():" + sb3.capacity());
System.out.println("sb3.length():" + sb3.length());
}
}
StringBuffer的添加功能
修飾符 返回值 方法名 參數(shù)列表
public StringBuffer append(String str) 可以把任意類型數(shù)據(jù)添加到字符串緩沖區(qū)里面,并返回字符串緩沖區(qū)本身
public StringBuffer insert(int offset,String str) 在指定位置把任意類型的數(shù)據(jù)插入到字符串緩沖區(qū)里面,并返回字符串緩沖區(qū)本身
public class StringBufferDemo {
public static void main(String[] args) {
// 創(chuàng)建字符串緩沖區(qū)對象
StringBuffer sb = new StringBuffer();
// public StringBuffer append(String str)
// StringBuffer sb2 = sb.append("hello");
// System.out.println("sb:" + sb);
// System.out.println("sb2:" + sb2); //sb1和sb2返回的結(jié)果一樣,因為StringBuffer相當(dāng)于一個杯子,返回字符串緩沖區(qū)本身
// System.out.println(sb == sb2); // true
// 一步一步的添加數(shù)據(jù)
// sb.append("hello");
// sb.append(true);
// sb.append(12);
// sb.append(34.56);
// 鏈?zhǔn)骄幊?要求返回的是一個對象,可以繼續(xù)執(zhí)行后邊的方法
sb.append("hello").append(true).append(12).append(34.56);
System.out.println("sb:" + sb);
// public StringBuffer insert(int offset,Stringstr) 在指定位置把任意類型的數(shù)據(jù)插入到字符串緩沖區(qū)里面,并返回字符串緩沖區(qū)本身
sb.insert(5, "world"); //從第五個位置插入,第五個位置的往后移
System.out.println("sb:" + sb);
}
}
StringBuffer的刪除功能
修飾符 返回值 方法名 參數(shù)列表
public StringBuffer deleteCharAt(int index) 刪除指定位置的字符佑惠,并返回本身
public StringBuffer delete(int start,int end) 刪除從指定位置開始指定位置結(jié)束的內(nèi)容,并返回本身(包含start,不包含end,包左不包右)
public class StringBufferDemo {
public static void main(String[] args) {
// 創(chuàng)建對象
StringBuffer sb = new StringBuffer();
// 添加功能
sb.append("hello").append("world").append("java");
System.out.println("sb:" + sb);
// public StringBuffer deleteCharAt(int index) 刪除指定位置的字符齐疙,并返回本身
// 需求:我要刪除e這個字符
// sb.deleteCharAt(1);
// 需求:我要刪除第一個l這個字符
// sb.deleteCharAt(1); //因為返回他本身
// public StringBuffer delete(int start,int end) 刪除從指定位置開始指定位置結(jié)束的內(nèi)容膜楷,并返回本身
// 需求:我要刪除world這個字符串
// sb.delete(5, 10); //包左不包右
// 需求:我要刪除所有的數(shù)據(jù)
sb.delete(0, sb.length()); //包左不包右
System.out.println("sb:" + sb);
}
}
StringBuffer的替換功能
修飾符 返回值 方法名 參數(shù)列表
public StringBuffer replace(int start,int end,String str) 從start開始到end用str替換,包左不包右
public class StringBufferDemo {
public static void main(String[] args) {
// 創(chuàng)建字符串緩沖區(qū)對象
StringBuffer sb = new StringBuffer();
// 添加數(shù)據(jù)
sb.append("hello");
sb.append("world");
sb.append("java");
System.out.println("sb:" + sb);
// public StringBuffer replace(int start,int end,String
// str):從start開始到end用str替換
// 需求:我要把world這個數(shù)據(jù)替換為"節(jié)日快樂"
sb.replace(5, 10, "節(jié)日快樂");
System.out.println("sb:" + sb);
}
}
StringBuffer的反轉(zhuǎn)功能
修飾符 返回值 方法名
public StringBuffer reverse() 將字符串反轉(zhuǎn)
public class StringBufferDemo {
public static void main(String[] args) {
// 創(chuàng)建字符串緩沖區(qū)對象
StringBuffer sb = new StringBuffer();
// 添加數(shù)據(jù)
sb.append("界世好你");
System.out.println("sb:" + sb);
// public StringBuffer reverse()
sb.reverse();
System.out.println("sb:" + sb);
}
}
StringBuffer的截取功能
修飾符 返回值 方法名 參數(shù)列表
public String substring(int start) 截取從start開始到末尾的字符,返回字符串類型
public String substring(int start,int end) 截取從start開始到end結(jié)束的字符,返回字符串類型(包左不包右)
注意返回值類型不再是StringBuffer本身了
public class StringBufferDemo {
public static void main(String[] args) {
// 創(chuàng)建字符串緩沖區(qū)對象
StringBuffer sb = new StringBuffer();
// 添加元素
sb.append("hello").append("world").append("java");
System.out.println("sb:" + sb);
// 截取功能
// public String substring(int start)
String s = sb.substring(5);
System.out.println("s:" + s);
System.out.println("sb:" + sb);
// public String substring(int start,int end)
String ss = sb.substring(5, 10);
System.out.println("ss:" + ss);
System.out.println("sb:" + sb);
}
}
String和StringBuffer的相互轉(zhuǎn)換
A -- B的轉(zhuǎn)換,我們把A轉(zhuǎn)換為B,其實是為了使用B的功能
B -- A的轉(zhuǎn)換,我們可能要的結(jié)果是A類型贞奋,所以還得轉(zhuǎn)回來
public class StringBufferTest {
public static void main(String[] args) {
// String -- StringBuffer
String s = "hello";
// 注意:不能把字符串的值直接賦值給StringBuffer
// StringBuffer sb = "hello";
// StringBuffer sb = s;
// 方式1:通過構(gòu)造方法
StringBuffer sb = new StringBuffer(s);
// 方式2:通過append()方法
StringBuffer sb2 = new StringBuffer();
sb2.append(s);
System.out.println("sb:" + sb);
System.out.println("sb2:" + sb2);
System.out.println("---------------");
// StringBuffer -- String
StringBuffer buffer = new StringBuffer("java");
// String(StringBuffer buffer)
// 方式1:通過構(gòu)造方法
String str = new String(buffer);
// 方式2:通過toString()方法
String str2 = buffer.toString();
System.out.println("str:" + str);
System.out.println("str2:" + str2);
}
}
/*
* 把數(shù)組拼接成一個字符串
*/
public class StringBufferTest2 {
public static void main(String[] args) {
// 定義一個數(shù)組
int[] arr = { 44, 33, 55, 11, 22 };
// 定義功能
// 方式1:用String做拼接的方式
String s1 = arrayToString(arr);
System.out.println("s1:" + s1);
// 方式2:用StringBuffer做拼接的方式
String s2 = arrayToString2(arr);
System.out.println("s2:" + s2);
}
// 用StringBuffer做拼接的方式
public static String arrayToString2(int[] arr) {
StringBuffer sb = new StringBuffer();
sb.append("[");
for (int x = 0; x < arr.length; x++) {
if (x == arr.length - 1) {
sb.append(arr[x]);
} else {
sb.append(arr[x]).append(", ");
}
}
sb.append("]");
return sb.toString();
}
// 用String做拼接的方式,會在方法區(qū)生成多個內(nèi)存空間存儲,浪費空間效率不高,用StringBuffer改進
public static String arrayToString(int[] arr) {
String s = "";
s += "[";
for (int x = 0; x < arr.length; x++) {
if (x == arr.length - 1) {
s += arr[x];
} else {
s += arr[x];
s += ", ";
}
}
s += "]";
return s;
}
}
public class StringBufferDemo {
/*
* 需求:反轉(zhuǎn)字符串
* 分析:對字符串進行反轉(zhuǎn)把将,但是StringBuffer中有反轉(zhuǎn)功能
* 先將字符串轉(zhuǎn)換為StringBuffer
* 再將StringBuffer反轉(zhuǎn)
* 最后將StringBuffer轉(zhuǎn)換為字符串
* */
public static void main(String[] args) {
//定義一個需要反轉(zhuǎn)的字符串
String str = "123456";
//將字符串轉(zhuǎn)換為StringBuffer
StringBuffer sb = new StringBuffer();
sb.append(str);
sb.reverse();
//再將StringBuffer轉(zhuǎn)換為String
str = sb.toString();
System.out.println(str);
}
}
import java.util.Scanner;
public class StringBufferDemo {
/*
* 需求:判斷字符串是否對稱,例:abc不對稱忆矛,abba,aba對稱
*分析:利用StringBuffer的反轉(zhuǎn)功能察蹲,看是否和之前的一樣
*
* */
public static void main(String[] args) {
//創(chuàng)建鍵盤輸入對象
Scanner sc = new Scanner(System.in);
System.out.println("情輸入待判斷的字符串");
String str = sc.nextLine();
System.out.println(isSame(str));
System.out.println(isSame2(str));
}
//定義判斷方法
public static boolean isSame(String str){
StringBuffer sb = new StringBuffer();
//將字符串轉(zhuǎn)為StringBuffer
sb.append(str);
//將StringBuffer反轉(zhuǎn)
sb.reverse();
//再將StringBuffer轉(zhuǎn)換為字符串
String sb1 = sb.toString();
//再將反轉(zhuǎn)后的與源字符串進行比較
boolean flag = sb1.equals(str);
return flag;
}
public static boolean isSame2(String str){
//相當(dāng)于isSame,鏈?zhǔn)骄幊? return new StringBuffer(str).reverse().toString().equals(str);
}
}
StringBuilder
是非同步,一般用于單線程催训,速度就比StringBuffer快
和StringBuffer用法一樣
String,StringBuffer,StringBuilder的區(qū)別
String是內(nèi)容不可變的洽议,而StringBuffer,StringBuilder都是內(nèi)容可變的
StringBuffer是同步的,數(shù)據(jù)安全,效率低;StringBuilder是不同步的,數(shù)據(jù)不安全,效率高
StringBuffer和數(shù)組的區(qū)別
二者都可以看出是一個容器漫拭,裝其他的數(shù)據(jù),但是StringBuffer的數(shù)據(jù)最終是一個字符串?dāng)?shù)據(jù),而數(shù)組可以放置多種數(shù)據(jù)亚兄,但必須是同一種數(shù)據(jù)類型的
String和StringBuffer作為形式參數(shù)問題
形式參數(shù):
基本類型:形式參數(shù)的改變不影響實際參數(shù)
引用類型:形式參數(shù)的改變直接影響實際參數(shù)
注意:
String作為參數(shù)傳遞,效果和基本類型作為參數(shù)傳遞是一樣的
Day13
數(shù)組的排序和查找
冒泡排序
相鄰元素兩兩比較采驻,大的往后放审胚,第一次完畢,最大值出現(xiàn)在了最大索引處
public class ArrayDemo {
public static void main(String[] args) {
// 定義一個數(shù)組
int[] arr = { 24, 69, 80, 57, 13 };
System.out.println("排序前:");
printArray(arr);
/*for (int x = 0; x < arr.length - 1; x++) {
for (int y = 0; y < arr.length - 1 - x; y++) {
if (arr[y] > arr[y + 1]) {
int temp = arr[y];
arr[y] = arr[y + 1];
arr[y + 1] = temp;
}
}
}
System.out.println("排序后:");
printArray(arr);
*/
//由于我可能有多個數(shù)組要排序礼旅,所以我要寫成方法
bubbleSort(arr);
System.out.println("排序后:");
printArray(arr);
}
//冒泡排序代碼
public static void bubbleSort(int[] arr){
for (int x = 0; x < arr.length - 1; x++) {
for (int y = 0; y < arr.length - 1 - x; y++) {
if (arr[y] > arr[y + 1]) {
int temp = arr[y];
arr[y] = arr[y + 1];
arr[y + 1] = temp;
}
}
}
}
// 遍歷功能
public static void printArray(int[] arr) {
System.out.print("[");
for (int x = 0; x < arr.length; x++) {
if (x == arr.length - 1) {
System.out.print(arr[x]);
} else {
System.out.print(arr[x] + ", ");
}
}
System.out.println("]");
}
}
選擇排序
從0索引開始膳叨,依次和后面元素比較,小的往前放痘系,第一次完畢菲嘴,最小值出現(xiàn)在了最小索引處
public class ArrayDemo {
public static void main(String[] args) {
// 定義一個數(shù)組
int[] arr = { 24, 69, 80, 57, 13 };
System.out.println("排序前:");
printArray(arr);
/*
//通過觀察發(fā)現(xiàn)代碼的重復(fù)度太高,所以用循環(huán)改進
for(int x=0; x<arr.length-1; x++){
for(int y=x+1; y<arr.length; y++){
if(arr[y] <arr[x]){
int temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
}
}
System.out.println("排序后:");
printArray(arr);
*/
//用方法改進
selectSort(arr);
System.out.println("排序后:");
printArray(arr);
}
public static void selectSort(int[] arr){
for(int x=0; x<arr.length-1; x++){
for(int y=x+1; y<arr.length; y++){
if(arr[y] <arr[x]){
int temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
}
}
}
// 遍歷功能
public static void printArray(int[] arr) {
System.out.print("[");
for (int x = 0; x < arr.length; x++) {
if (x == arr.length - 1) {
System.out.print(arr[x]);
} else {
System.out.print(arr[x] + ", ");
}
}
System.out.println("]");
}
}
二分查找
查找:
基本查找:數(shù)組元素?zé)o序(從頭找到尾)
二分查找(折半查找):數(shù)組元素有序
/*
* 需求:鍵盤獲取一個整型數(shù)組,進行二分查找
* 分析:
* 進行二分查找的前提是有序數(shù)組龄坪,先對數(shù)組進行排序,在進行查找
* */
public class ArrDemo {
public static void main(String[] args) {
System.out.println("請輸入八個整數(shù)");
Scanner sc = new Scanner(System.in);
int[] arr = new int[8];
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
print(arr);
arr = maoPao(arr);
print(arr);
System.out.println("請輸入你想找的數(shù)");
int num =sc.nextInt();
int index = erFen(arr,num);
System.out.println("索引是"+index);
}
//遍歷數(shù)組的方法
public static void print(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
//對數(shù)組進行排序
public static int[] maoPao(int[] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length - 1; j++) {
if (arr[j] > arr[j + 1]) {
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
return arr;
}
//二分查找
public static int erFen(int[] arr, int num) {
int max = arr.length - 1;
int min = 0;
int mid = (max + min) / 2;
while (arr[mid] != num) {
if (arr[mid] > num) {
max = mid - 1;
} else if (arr[mid] < num) {
min = mid + 1;
}
mid = (max + min) / 2;
if (min > max){
return -1;
}
}
return mid;
}
}
注意:上面這種做法是有問題的
因為數(shù)組本身是無序的昭雌,所以這種情況下的查找不能使用二分查找,所以你先排序了健田,但是你排序的時候已經(jīng)改變了我最原始的元素索引
Arrays
針對數(shù)組操作的工具類:比如排序和查找
修飾符 返回值 方法名 參數(shù)列表(static修飾烛卧,靜態(tài)的,通過類名調(diào)用)
public static String toString(int[] a) 把任意類型數(shù)組數(shù)組轉(zhuǎn)成字符串妓局,以int舉例
public static void sort(int[] a) 對任意類型數(shù)組進行排序
public static int binarySearch(int[] a,int key) 二分查找
public class ArraysDemo {
public static void main(String[] args) {
// 定義一個數(shù)組
int[] arr = { 24, 69, 80, 57, 13 };
// public static String toString(int[] a) 把數(shù)組轉(zhuǎn)成字符串
System.out.println("排序前:" + Arrays.toString(arr));
// public static void sort(int[] a) 對數(shù)組進行排序
Arrays.sort(arr);
System.out.println("排序后:" + Arrays.toString(arr));
// [13, 24, 57, 69, 80]
// public static int binarySearch(int[] a,int key) 二分查找
System.out.println("binarySearch:" + Arrays.binarySearch(arr, 57));
System.out.println("binarySearch:" + Arrays.binarySearch(arr, 577));
}
}
Integer
修飾符 返回值 方法名 參數(shù)列表(靜態(tài)的唱星,通過類名直接調(diào)用)
public static String toBinaryString(int i) 將十進制轉(zhuǎn)換為二進制
public static String toOctalString(int i) 將十進制轉(zhuǎn)換為八進制
public static String toHexString(int i) 將十進制轉(zhuǎn)換為十六進制
十進制到其他進制
public static String toString(int i,int radix)進制的范圍:2-36
其他進制到十進制
public static int parseInt(String s,int radix)
public static final int MAX_VALUE Int的最大范圍
public static final int MIN_VALUE Int的最小范圍
包裝類類型
為了對基本數(shù)據(jù)類型進行更多的操作,更方便的操作跟磨,Java就針對每一種基本數(shù)據(jù)類型提供了對應(yīng)的類類型间聊,包裝類類型
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
Integer類的構(gòu)造方法
public Integer(int i)
public Integer(String s)
注意:這個字符串必須是由數(shù)字字符組成
public class IntegerDemo {
public static void main(String[] args) {
// 方式1
int i = 100;
Integer ii = new Integer(i);
System.out.println("ii:" + ii);
// 方式2
String s = "100";
// NumberFormatException
// String s = "abc";
Integer iii = new Integer(s);
System.out.println("iii:" + iii);
}
}
int類型和String類型的相互轉(zhuǎn)換
int類型和String類型的相互轉(zhuǎn)換
int -- String
String.valueOf(int i) 將int類型的轉(zhuǎn)換成String類型
String -- int
Integer.parseInt(String s) 將String類型轉(zhuǎn)換成Int類型
要想將字符串類型轉(zhuǎn)換成基本數(shù)據(jù)類型,就去找基本類型的包裝類里的parselnt
public class IntegerDemo {
public static void main(String[] args) {
// int -- String
int number = 100;
// 方式1,直接拼接
String s1 = "" + number;
System.out.println("s1:" + s1);
// 方式2,調(diào)用String類的valueOf方法
String s2 = String.valueOf(number);
System.out.println("s2:" + s2);
// 方式3
// int -- Integer -- String
Integer i = new Integer(number);
String s3 = i.toString();
System.out.println("s3:" + s3);
// 方式4
// public static String toString(int i)
String s4 = Integer.toString(number);
System.out.println("s4:" + s4);
System.out.println("-----------------");
// String -- int
String s = "100";
// 方式1
// String -- Integer -- int
Integer ii = new Integer(s);
// public int intValue()
int x = ii.intValue();
System.out.println("x:" + x);
//方式2
//public static int parseInt(String s)
int y = Integer.parseInt(s);
System.out.println("y:"+y);
}
}
JDK5的新特性
自動裝箱:把基本類型轉(zhuǎn)換為包裝類類型
自動拆箱:把包裝類類型轉(zhuǎn)換為基本類型
注意一個小問題:
在使用時,Integer x = null;代碼就會出現(xiàn)NullPointerException空指針異常抵拘,建議先判斷是否為null哎榴,然后再使用
public class IntegerDemo {
public static void main(String[] args) {
// 定義了一個int類型的包裝類類型變量i
// Integer i = new Integer(100);
Integer ii = 100;
ii += 200;
System.out.println("ii:" + ii);
// 通過反編譯后的代碼
// Integer ii = Integer.valueOf(100); //自動裝箱
// ii = Integer.valueOf(ii.intValue() + 200); //自動拆箱,再自動裝箱
// System.out.println((new StringBuilder("ii:")).append(ii).toString());
Integer iii = null;
// NullPointerException
if (iii != null) {
iii += 1000;
System.out.println(iii);
}
}
}
Character 類
在對象中包裝一個基本類型 char 的值僵蛛,此外尚蝌,該類提供了幾種方法,以確定字符的類別(小寫字母充尉,數(shù)字飘言,等等),并將字符從大寫轉(zhuǎn)換成小寫驼侠,反之亦然
構(gòu)造方法:
Character(char value)
成員方法:
public static boolean isUpperCase(char ch):判斷給定的字符是否是大寫字符
public static boolean isLowerCase(char ch):判斷給定的字符是否是小寫字符
public static boolean isDigit(char ch):判斷給定的字符是否是數(shù)字字符
public static char toUpperCase(char ch):把給定的字符轉(zhuǎn)換為大寫字符
public static char toLowerCase(char ch):把給定的字符轉(zhuǎn)換為小寫字符
* 統(tǒng)計一個字符串中大寫字母字符姿鸿,小寫字母字符,數(shù)字字符出現(xiàn)的次數(shù)(不考慮其他字符)
/*
* 分析:
* A:定義三個統(tǒng)計變量倒源。
* int bigCont=0;
* int smalCount=0;
* int numberCount=0;
* B:鍵盤錄入一個字符串苛预。
* C:把字符串轉(zhuǎn)換為字符數(shù)組。
* D:遍歷字符數(shù)組獲取到每一個字符
* E:判斷該字符是
* 大寫 bigCount++;
* 小寫 smalCount++;
* 數(shù)字 numberCount++;
* F:輸出結(jié)果即可
*/
public class CharacterTest {
public static void main(String[] args) {
// 定義三個統(tǒng)計變量笋熬。
int bigCount = 0;
int smallCount = 0;
int numberCount = 0;
// 鍵盤錄入一個字符串热某。
Scanner sc = new Scanner(System.in);
System.out.println("請輸入一個字符串:");
String line = sc.nextLine();
// 把字符串轉(zhuǎn)換為字符數(shù)組。
char[] chs = line.toCharArray();
// 歷字符數(shù)組獲取到每一個字符
for (int x = 0; x < chs.length; x++) {
char ch = chs[x];
// 判斷該字符
if (Character.isUpperCase(ch)) {
bigCount++;
} else if (Character.isLowerCase(ch)) {
smallCount++;
} else if (Character.isDigit(ch)) {
numberCount++;
}
}
// 輸出結(jié)果即可
System.out.println("大寫字母:" + bigCount + "個");
System.out.println("小寫字母:" + smallCount + "個");
System.out.println("數(shù)字字符:" + numberCount + "個");
}
}
Day14
對數(shù)字進行校驗
/*
* 需求:檢驗數(shù)字胳螟,長度在5-15之間昔馋,且不能以0開頭的一串?dāng)?shù)字
* 分析:
* 鍵盤獲取一串?dāng)?shù)字
* 判斷長度是否是5-15之間
* 判斷是否以0開頭
* 判斷整體是不是數(shù)字
* */
public class Checkdigit {
public static void main(String[] args) {
//創(chuàng)建對象
Scanner sc = new Scanner(System.in);
String num = sc.nextLine();
boolean falg = checkNum(num);
if (falg){
System.out.println("輸入正確");
}else
System.out.println("輸入有誤");
}
//定義方法判斷
public static boolean checkNum(String num){
//定義判斷位
boolean flag = true;
//判斷長度是不是在5-15之間
if ((num.length()>= 5) && (num.length()<= 15)){
//判斷首字符是否為0
if (!(num.startsWith("0"))){
//判斷輸入的是否全是數(shù)字
for (int i = 0; i < num.length(); i++) {
//獲取每一位的字符
char ch = num.charAt(i);
//判斷字符是否為數(shù)字
flag = Character.isDigit(ch);
break;
}
}else
flag = false;
}else
flag = false;
return flag;
}
}
正則表達式
格式:String regex = " "; 雙引號里邊的是規(guī)則
字符
x 字符 x,舉例:'a'表示字符a
\ 反斜線字符 反斜杠代表轉(zhuǎn)義糖耸,再來一個反斜杠代表反斜杠
\n 新行(換行)符 ('\u000A')
\r 回車符 ('\u000D')
字符類
[abc] a秘遏、b 或 c(簡單類) 表示是a或是b或是c,三個選一個
[^abc] 任何字符蔬捷,除了 a垄提、b 或 c(否定)
[a-zA-Z] a到 z 或 A到 Z,兩頭的字母包括在內(nèi)(范圍)所有的大小寫字符
[0-9] 0到9的字符都包括
預(yù)定義字符類
. 任何字符周拐, .轉(zhuǎn)義一下表示字符.
\d 數(shù)字:[0-9]
\w 單詞字符:[a-zA-Z_0-9]铡俐,在正則表達式里面組成單詞的東西必須有這些東西組成
邊界匹配器
^ 行的開頭
$ 行的結(jié)尾
\b 單詞邊界,就是不是單詞字符的地方
舉例:hello world?haha;xixi(空格 妥粟?审丘;表示單詞邊界)
Greedy 數(shù)量詞
X? X,一次或一次也沒有勾给,零次或一次
X* X滩报,零次或多次,包括一次
X+ X播急,一次或多次脓钾,至少一次
X{n} X,恰好 n 次
X{n,} X桩警,至少 n 次
X{n,m} X可训,至少 n 次,但是不超過 m 次
用正則表達式改進數(shù)字校驗案例
/*
* 需求:檢驗數(shù)字捶枢,長度在5-15之間握截,且不能以0開頭的一串?dāng)?shù)字
* 分析:
* 鍵盤獲取一串?dāng)?shù)字
* 判斷長度是否是5-15之間
* 判斷是否以0開頭
* 判斷整體是不是數(shù)字
* */
public class Checkdigit {
public static void main(String[] args) {
//創(chuàng)建對象
Scanner sc = new Scanner(System.in);
String num = sc.nextLine();
boolean falg = checkNum(num);
if (falg){
System.out.println("輸入正確");
}else
System.out.println("輸入有誤");
}
//定義方法判斷
public static boolean checkNum(String num){
//定義判斷位
boolean flag = true;
flag = num.matches("[1-9][0-9]{4,14}");
//[1-9]表示第一位從1-9
//[0-9]表示除了第一位其他的是0-9的數(shù)字
//{4,14}表示0-9的范圍是4~14之間烂叔,[1-9]沒有跟表示長度的谨胞,默認(rèn)1位,4~14 + 1 5~15的范圍
return flag;
//可以在改進蒜鸡,matches返回的是一個布爾值的類型胯努,可以直接return返回
//return num.matches("[1-9][0-9]{4,14}");
}
}
正則表達式的應(yīng)用
判斷功能
String類的public boolean matches(String regex)判斷字符串是否滿足正則表達式(regex規(guī)則)的規(guī)則,返回布爾值類型
/*
*
* 需求:
* 判斷手機號碼是否滿足要求?
*
* 分析:
* A:鍵盤錄入手機號碼
* B:定義手機號碼的規(guī)則
* 13436975980
* 13688886868
* 13866668888
* 13456789012
* 13123456789
* 18912345678
* 18886867878
* 18638833883
* C:調(diào)用功能逢防,判斷即可
* D:輸出結(jié)果
*/
public class RegexDemo {
public static void main(String[] args) {
//鍵盤錄入手機號碼
Scanner sc = new Scanner(System.in);
System.out.println("請輸入你的手機號碼:");
String phone = sc.nextLine();
//定義手機號碼的規(guī)則
String regex = "1[38]\\d{9}";
//調(diào)用功能康聂,判斷即可
boolean flag = phone.matches(regex);
//輸出結(jié)果
System.out.println("flag:"+flag);
}
}
分割功能
String類的public String[] split(String regex),根據(jù)給定正則表達式(regex規(guī)則)的匹配拆分此字符串
/*
* 分割功能練習(xí)
*/
public class RegexDemo2 {
public static void main(String[] args) {
// 定義一個字符串
String s1 = "aa,bb,cc";
// 直接分割
String[] str1Array = s1.split(",");
for (int x = 0; x < str1Array.length; x++) {
System.out.println(str1Array[x]);
}
System.out.println("---------------------");
String s2 = "aa.bb.cc";
String[] str2Array = s2.split("\\."); //.代表所有字符胞四,所以需要轉(zhuǎn)義
for (int x = 0; x < str2Array.length; x++) {
System.out.println(str2Array[x]);
}
System.out.println("---------------------");
String s3 = "aa bb cc";
String[] str3Array = s3.split(" +"); //表示一個及以上的空格
for (int x = 0; x < str3Array.length; x++) {
System.out.println(str3Array[x]);
}
System.out.println("---------------------");
//硬盤上的路徑恬汁,我們應(yīng)該用\\替代\
String s4 = "E:\\JavaSE\\day14\\avi";
String[] str4Array = s4.split("\\\\");// s4里邊的\\需要用\\\\代替
for (int x = 0; x < str4Array.length; x++) {
System.out.println(str4Array[x]);
}
System.out.println("---------------------");
}
}
/*
* 需求:我有一個字符串“97 28 63 12 88”
* 想要輸出為“12 28 63 88 97”
* 分析:輸出的是排序后的,但是不能對字符串進行排序辜伟,所以要將字符串轉(zhuǎn)換為整型數(shù)組
* 可以用分割得到每一個位置的數(shù)存放到數(shù)組中
* 在進行排序
* 在組裝成字符串
* 輸出
* */
public class RegexTest {
public static void main(String[] args) {
//定義字符串
String str = "97 28 63 12 88";
//定義規(guī)則
String regex = " ";
//分割字符串String類的public String[] split(String regex)
String [] strings = str.split(regex);
//定義整型數(shù)組接收字符串?dāng)?shù)組的值,用字符串的長度定義整型數(shù)組的長度
int [] arr = new int[strings.length];
for (int i = 0; i < strings.length; i++) {
//Integer.parseInt(String s)將String轉(zhuǎn)換成int類型
arr[i] = Integer.parseInt(strings[i]);
}
//對數(shù)組arr進行排序
//冒泡排序
/*for (int i = 0; i < arr.length-1; i++) {
for (int j = 0; j < arr.length-1-i; j++) {
if (arr[j] > arr[j+1]){
int tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;
}
}
}*/
Arrays.sort(arr); //對數(shù)組進行排序氓侧,底層邏輯是快速排序
//將int轉(zhuǎn)成String
/*String s = "";
for (int i = 0; i < arr.length; i++) {
s += arr[i]+" ";
}*/
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
//先添加數(shù)在添加空格
sb.append(arr[i]).append(" ");
}
//將sb轉(zhuǎn)成string在去除空格
String s = sb.toString().trim();
System.out.println(s);
}
}
替換功能
String類的public String replaceAll(String regex,String replacement),使用給定的 replacement 替換此字符串所有匹配給定的正則表達式(regex規(guī)則)的子字符串
/*
*需求:定義一個字符串橄霉,不允許出現(xiàn)數(shù)字渺鹦,出現(xiàn)的話用*替換
*/
public class RegexDemo {
public static void main(String[] args) {
// 定義一個字符串
String s = "helloqq12345worldkh622112345678java";
// 我要去除所有的數(shù)字,用*給替換掉
// String regex = "\\d+"; //一個或多個數(shù)字用一個*代替
// String regex = "\\d"; //每一個數(shù)字用*代替
//String ss = "*"; //用*代替數(shù)字
// 直接把數(shù)字去掉
String regex = "\\d+";
String ss = "";
String result = s.replaceAll(regex, ss); //將字符串s中符合regex規(guī)則的替換成ss
System.out.println(result);
}
}
獲取功能
Pattern(模式)和Matcher(匹配器)類的使用
模式和匹配器的基本使用順序
// 把正則表達式("ab")編譯成模式對象
Pattern p = Pattern.compile("ab");
// 通過模式對象得到匹配器對象,這個時候需要的是被匹配的字符串("aaaaab")
Matcher m = p.matcher("aaaaab");
// 調(diào)用匹配器對象的功能
boolean b = m.matches();
System.out.println(b);
/*
* 獲取下面這個字符串中由三個字符組成的單詞
* da jia ting wo shuo,jin tian yao xia yu,bu shang wan zi xi,gao xing bu?
*/
public class RegexDemo2 {
public static void main(String[] args) {
// 定義字符串
String s = "da jia ting wo shuo,jin tian yao xia yu,bu shang wan zi xi,gao xing bu?";
// 規(guī)則,三個字符的長度司训,左右都是單詞邊界
String regex = "\\b\\w{3}\\b";
// 把規(guī)則編譯成模式對象
Pattern p = Pattern.compile(regex);
// 通過模式對象得到匹配器對象
Matcher m = p.matcher(s);
// 調(diào)用匹配器對象的功能
// 通過find方法就是查找有沒有滿足條件的子串
// public boolean find()
// boolean flag = m.find();
// System.out.println(flag);
// // 如何得到值呢?
// // public String group()
// String ss = m.group();
// System.out.println(ss);
//
// // 再來一次
// flag = m.find();
// System.out.println(flag);
// ss = m.group();
// System.out.println(ss);
while (m.find()) {
System.out.println(m.group());
}
// 注意:一定要先find()旱捧,然后才能group()
// IllegalStateException: No match found
// String ss = m.group();
// System.out.println(ss);
}
}
Math類
用于數(shù)學(xué)運算的類
成員變量:
public static final double PI 圓周率
public static final double E 自然對數(shù)
成員方法:
public static int abs(int a):絕對值
public static double ceil(double a):向上取整就是有小數(shù)部分的去掉小數(shù)独郎,整數(shù)加一踩麦,例12.34 和12.56都是13.0
public static double floor(double a):向下取整就是有小數(shù)部分的去掉小數(shù),例12.34 和12.56都是12.0
public static int max(int a,int b):最大值
public static int max(int a,int b):最小值
public static double pow(double a,double b):a的b次冪
public static double random():隨機數(shù) (0.0,1.0)氓癌,包左不包右
public static int round(float a) 對float四舍五入谓谦,返回int
public static long round(double a) 對double四舍五入,返回long
public static double sqrt(double a):正平方根
public class MathDemo {
public static void main(String[] args) {
// public static final double PI
System.out.println("PI:" + Math.PI);
// public static final double E
System.out.println("E:" + Math.E);
System.out.println("--------------");
// public static int abs(int a):絕對值
System.out.println("abs:" + Math.abs(10));
System.out.println("abs:" + Math.abs(-10));
System.out.println("--------------");
// public static double ceil(double a):向上取整
System.out.println("ceil:" + Math.ceil(12.34));
System.out.println("ceil:" + Math.ceil(12.56));
System.out.println("--------------");
// public static double floor(double a):向下取整
System.out.println("floor:" + Math.floor(12.34));
System.out.println("floor:" + Math.floor(12.56));
System.out.println("--------------");
// public static int max(int a,int b):最大值
System.out.println("max:" + Math.max(12, 23));
// 需求:我要獲取三個數(shù)據(jù)中的最大值
// 方法的嵌套調(diào)用
System.out.println("max:" + Math.max(Math.max(12, 23), 18));
// 需求:我要獲取四個數(shù)據(jù)中的最大值
System.out.println("max:"
+ Math.max(Math.max(12, 78), Math.max(34, 56)));
System.out.println("--------------");
// public static double pow(double a,double b):a的b次冪
System.out.println("pow:" + Math.pow(2, 3));
System.out.println("--------------");
// public static double random():隨機數(shù) [0.0,1.0)
System.out.println("random:" + Math.random());
// 獲取一個1-100之間的隨機數(shù)
System.out.println("random:" + ((int) (Math.random() * 100) + 1));
System.out.println("--------------");
// public static int round(float a) 四舍五入(參數(shù)為double的自學(xué))
System.out.println("round:" + Math.round(12.34f));
System.out.println("round:" + Math.round(12.56f));
System.out.println("--------------");
//public static double sqrt(double a):正平方根
System.out.println("sqrt:"+Math.sqrt(4));
}
}
獲取指定范圍內(nèi)的隨機數(shù)
import java.util.Random;
import java.util.Scanner;
/*
* 需求:獲取指定范圍內(nèi)的隨機數(shù)贪婉,例獲取100-200之間的隨機數(shù)
* 分析:鍵盤獲取開始和結(jié)束的范圍
* 定義一個方法找到開始和結(jié)束范圍內(nèi)的隨機數(shù)
* 輸出隨機數(shù)
* */
public class RandomTest {
public static void main(String[] args) {
//鍵盤獲取開始和結(jié)束的范圍
Scanner sc = new Scanner(System.in);
System.out.println("請輸入開始的范圍");
int start = sc.nextInt();
System.out.println("請輸入結(jié)束的范圍");
int end = sc.nextInt();
//多調(diào)用幾次看是否在范圍內(nèi)
for (int i = 0; i < 100; i++) {
System.out.println(RandowNum(start, end));
}
}
//定義方法反粥,明確返回值類型int,明確參數(shù)列表start,end
public static int RandowNum(int start, int end) {
Random r = new Random();
//結(jié)束位置減去開始位置在加上開始的位置加一
//例:100-300 300-100 + 100
//就是 0-200之間 +100 就是100 - 300
int i = r.nextInt(end - start) + start + 1;
return i;
}
}
Random類
產(chǎn)生隨機數(shù)的類
構(gòu)造方法:
public Random():沒有給種子疲迂,用的是默認(rèn)種子才顿,是當(dāng)前時間的毫秒值
public Random(long seed):給出指定的種子
注意給定種子后,每次得到的隨機數(shù)是相同的
成員方法:
public int nextInt():返回的是int范圍內(nèi)的隨機數(shù)
public int nextInt(int n):返回的是[0,n)范圍的內(nèi)隨機數(shù)
System類
包含一些有用的類字段和方法尤蒿,它不能被實例化郑气。
方法:
public static void gc():運行垃圾回收器
public static void exit(int status)終止當(dāng)前正在運行的 Java 虛擬機。參數(shù)用作狀態(tài)碼腰池;根據(jù)慣例竣贪,非 0 的狀態(tài)碼表示異常終止
public static long currentTimeMillis()返回以毫秒為單位的當(dāng)前時間,可以用來統(tǒng)計程序運行多少秒
public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)從指定源數(shù)組中復(fù)制一個數(shù)組,復(fù)制從指定的位置開始巩螃,到目標(biāo)數(shù)組的指定位置結(jié)束(從原數(shù)組src的srcPos位置開始,復(fù)制到目標(biāo)數(shù)組dest的destPos位置.復(fù)制length個,會覆蓋目標(biāo)數(shù)組位置的數(shù))
//統(tǒng)計程序運行時間
long start = System.currentTimeMillis();
for (int x = 0; x < 100000; x++) {
System.out.println("hello" + x);
}
long end = System.currentTimeMillis();
System.out.println("共耗時:" + (end - start) + "毫秒");
BigInteger類
可以讓超過Integer范圍(-2147483648 至 2147483647)內(nèi)的數(shù)據(jù)進行運算
構(gòu)造方法:
BigInteger(String val)
BigInteger bi = new BigInteger("2147483648"); //超過Integer范圍
System.out.println("bi:" + bi);
成員方法
public BigInteger add(BigInteger val):加
public BigInteger subtract(BigInteger val):減
public BigInteger multiply(BigInteger val):乘
public BigInteger divide(BigInteger val):除
public BigInteger[] divideAndRemainder(BigInteger val):返回商和余數(shù)的數(shù)組
public class BigIntegerDemo {
public static void main(String[] args) {
BigInteger bi1 = new BigInteger("100");
BigInteger bi2 = new BigInteger("50");
// public BigInteger add(BigInteger val):加
System.out.println("add:" + bi1.add(bi2));
// public BigInteger subtract(BigInteger val):加
System.out.println("subtract:" + bi1.subtract(bi2));
// public BigInteger multiply(BigInteger val):加
System.out.println("multiply:" + bi1.multiply(bi2));
// public BigInteger divide(BigInteger val):加
System.out.println("divide:" + bi1.divide(bi2));
// public BigInteger[] divideAndRemainder(BigInteger val):返回商和余數(shù)的數(shù)組
BigInteger[] bis = bi1.divideAndRemainder(bi2);
System.out.println("商:" + bis[0]);
System.out.println("余數(shù):" + bis[1]);
}
}
BigDecimal類
不可變的演怎、任意精度的有符號十進制數(shù),可以解決數(shù)據(jù)丟失問題
由于在運算的時候,float類型和double很容易丟失精度避乏,所以爷耀,為了能精確的表示、計算浮點數(shù)拍皮,Java提供了BigDecimal
構(gòu)造方法:
public BigDecimal(String val)
成員方法:
public BigDecimal add(BigDecimal augend)加
public BigDecimal subtract(BigDecimal subtrahend)減
public BigDecimal multiply(BigDecimal multiplicand)乘
public BigDecimal divide(BigDecimal divisor)除
public BigDecimal divide(BigDecimal divisor,int scale,int roundingMode):divisor商歹叮,scale保留幾位小數(shù),roundingMode如何舍取,其中ROUND_HALF_UP最接近四舍五入
public class BigDecimalDemo {
public static void main(String[] args) {
// System.out.println(0.09 + 0.01);
// System.out.println(1.0 - 0.32);
// System.out.println(1.015 * 100);
// System.out.println(1.301 / 100);
BigDecimal bd1 = new BigDecimal("0.09");
BigDecimal bd2 = new BigDecimal("0.01");
System.out.println("add:" + bd1.add(bd2));
System.out.println("-------------------");
BigDecimal bd3 = new BigDecimal("1.0");
BigDecimal bd4 = new BigDecimal("0.32");
System.out.println("subtract:" + bd3.subtract(bd4));
System.out.println("-------------------");
BigDecimal bd5 = new BigDecimal("1.015");
BigDecimal bd6 = new BigDecimal("100");
System.out.println("multiply:" + bd5.multiply(bd6));
System.out.println("-------------------");
BigDecimal bd7 = new BigDecimal("1.301");
BigDecimal bd8 = new BigDecimal("100");
System.out.println("divide:" + bd7.divide(bd8));
System.out.println("divide:"
+ bd7.divide(bd8, 3, BigDecimal.ROUND_HALF_UP));
System.out.println("divide:"
+ bd7.divide(bd8, 8, BigDecimal.ROUND_HALF_UP));
}
}
Date類
表示特定的瞬間铆帽,精確到毫秒
構(gòu)造方法:
Date():根據(jù)當(dāng)前的默認(rèn)毫秒值創(chuàng)建日期對象
Date(long date):根據(jù)給定的毫秒值創(chuàng)建日期對象
public class DateDemo {
public static void main(String[] args) {
// 創(chuàng)建對象
Date d = new Date();
System.out.println("d:" + d);
// 創(chuàng)建對象
// long time = System.currentTimeMillis(); //獲取當(dāng)前程序運行時的時間
long time = 1000 * 60 * 60; // 1小時+東八區(qū)的8小時
Date d2 = new Date(time);
System.out.println("d2:" + d2);
}
}
成員方法
public long getTime():獲取時間咆耿,以毫秒為單位
public void setTime(long time):設(shè)置時間
從Date得到一個毫秒值
getTime()
把一個毫秒值轉(zhuǎn)換為Date
構(gòu)造方法
setTime(long time)
public class DateDemo {
public static void main(String[] args) {
// 創(chuàng)建對象
Date d = new Date();
// 獲取時間
long time = d.getTime();
System.out.println(time);
// System.out.println(System.currentTimeMillis());
System.out.println("d:" + d);
// 設(shè)置時間
d.setTime(1000);
System.out.println("d:" + d);
}
}
Date --String(格式化)
public final String format(Date date)
String -- Date(解析)
public Date parse(String source)
DateForamt:可以進行日期和字符串的格式化和解析,但是由于是抽象類爹橱,所以使用具體子類SimpleDateFormat
SimpleDateFormat
SimpleDateFormat的構(gòu)造方法:
SimpleDateFormat():默認(rèn)模式
SimpleDateFormat(String pattern):給定的模式
這個模式字符串該如何寫呢?
通過查看API萨螺,我們就找到了對應(yīng)的模式
年 y
月 M
日 d
時 H
分 m
秒 s
public class DateFormatDemo {
public static void main(String[] args) throws ParseException {
// Date -- String
// 創(chuàng)建日期對象
Date d = new Date();
// 創(chuàng)建格式化對象
// SimpleDateFormat sdf = new SimpleDateFormat();
// 給定模式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
// public final String format(Date date)
String s = sdf.format(d);
System.out.println(s);
//String -- Date
String str = "2022-03-14 16:48:02";
//在把一個字符串解析為日期的時候,請注意格式必須和給定的字符串格式匹配
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dd = sdf2.parse(str);
System.out.println(dd);
}
}
計算你出生多少天了
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
/*
* 需求:算出你來到這個世界多少天
* 分析:首先鍵盤輸入自己的出生年月
* 將出生年月?lián)Q成毫秒 String -- Date
* 獲取系統(tǒng)當(dāng)前時間
* 用當(dāng)前時間減去出生時的毫秒值
* 對毫秒值計算得出天數(shù)
* */
public class dateToString {
public static void main(String[] args) throws ParseException {
//首先鍵盤輸入自己的出生年月
Scanner sc = new Scanner(System.in);
System.out.println("請輸入自己的出生年月日愧驱,用-隔開");
String birthDay = sc.nextLine();
//將出生年月?lián)Q成毫秒 String -- Date
//創(chuàng)建格式化對象
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
//把該字符串轉(zhuǎn)換為一個日期
Date birth = sd.parse(birthDay);
//再把日期轉(zhuǎn)換為毫秒
long myTime = birth.getTime();
//獲取系統(tǒng)當(dāng)前時間
Date d = new Date();
long dateTime = d.getTime();
//用當(dāng)前時間減去出生時的毫秒值
myTime = dateTime - myTime;
//在對毫秒值進行運算得出多少天
int day = (int)(myTime/1000/60/60/24);
System.out.println("你出生了"+day+"天");
}
}
Calendar
它為特定瞬間與一組諸如 YEAR慰技、MONTH、DAY_OF_MONTH组砚、HOUR 等 日歷字段之間的轉(zhuǎn)換提供了一些方法吻商,并為操作日歷字段(例如獲得下星期的日期)提供了一些方法
public int get(int field):返回給定日歷字段的值,日歷類中的每個日歷字段都是靜態(tài)的成員變量,并且是int類型
//獲取當(dāng)前時間的年月日
public class CalendarDemo {
public static void main(String[] args) {
// 其日歷字段已由當(dāng)前日期和時間初始化:
Calendar rightNow = Calendar.getInstance(); // 子類對象,多態(tài)
// 獲取年
int year = rightNow.get(Calendar.YEAR);
// 獲取月
int month = rightNow.get(Calendar.MONTH);
// 獲取日
int date = rightNow.get(Calendar.DATE);
System.out.println(year + "年" + (month + 1) + "月" + date + "日");
}
}
成員方法
public void add(int field,int amount):根據(jù)給定的日歷字段和對應(yīng)的時間糟红,來對當(dāng)前的日歷進行操作
public final void set(int year,int month,int date):設(shè)置當(dāng)前日歷的年月日
public class CalendarDemo {
public static void main(String[] args) {
// 獲取當(dāng)前的日歷時間
Calendar c = Calendar.getInstance();
// 獲取年
int year = c.get(Calendar.YEAR);
// 獲取月
int month = c.get(Calendar.MONTH);
// 獲取日
int date = c.get(Calendar.DATE);
System.out.println(year + "年" + (month + 1) + "月" + date + "日");
// // 三年前的今天
// c.add(Calendar.YEAR, -3);
// // 獲取年
// year = c.get(Calendar.YEAR);
// // 獲取月
// month = c.get(Calendar.MONTH);
// // 獲取日
// date = c.get(Calendar.DATE);
// System.out.println(year + "年" + (month + 1) + "月" + date + "日");
// 5年后的10天前
c.add(Calendar.YEAR, 5);
c.add(Calendar.DATE, -10);
// 獲取年
year = c.get(Calendar.YEAR);
// 獲取月
month = c.get(Calendar.MONTH);
// 獲取日
date = c.get(Calendar.DATE);
System.out.println(year + "年" + (month + 1) + "月" + date + "日");
System.out.println("--------------");
c.set(2011, 11, 11);
// 獲取年
year = c.get(Calendar.YEAR);
// 獲取月
month = c.get(Calendar.MONTH);
// 獲取日
date = c.get(Calendar.DATE);
System.out.println(year + "年" + (month + 1) + "月" + date + "日");
}
}
/*
* 獲取任意一年的二月有多少天
*
* 分析:
* A:鍵盤錄入任意的年份
* B:設(shè)置日歷對象的年月日
* 年就是A輸入的數(shù)據(jù)
* 月是2
* 日是1
* C:把時間往前推一天艾帐,就是2月的最后一天
* D:獲取這一天輸出即可
*/
public class CalendarTest {
public static void main(String[] args) {
// 鍵盤錄入任意的年份
Scanner sc = new Scanner(System.in);
System.out.println("請輸入年份:");
int year = sc.nextInt();
// 設(shè)置日歷對象的年月日
Calendar c = Calendar.getInstance();
c.set(year, 2, 1); // 其實是這一年的3月1日
// 把時間往前推一天乌叶,就是2月的最后一天
c.add(Calendar.DATE, -1);
// 獲取這一天輸出即可
System.out.println(c.get(Calendar.DATE));
}
}
package Array;
/*
* 需求:我有五個學(xué)生,把五個學(xué)生的信息存儲到數(shù)組中柒爸,并進行遍歷數(shù)組
* 分析: 有五個學(xué)生准浴,肯定要定義一個學(xué)生類
* 創(chuàng)建五個學(xué)生對象
* 要有一個學(xué)生數(shù)組
* 把五個對象存放到學(xué)生數(shù)組中
* 遍歷數(shù)組
* */
public class StudentDemo {
public static void main(String[] args) {
//創(chuàng)建學(xué)生對象并賦值
Student s1 = new Student("張三",18);
Student s2 = new Student("李四",16);
Student s3 = new Student("王五",19);
Student s4 = new Student("趙六",15);
Student s5 = new Student("周七",20);
//要有一個學(xué)生數(shù)組
Student [] students = new Student[5];
//把五個對象存放到學(xué)生數(shù)組中,不可以用for循環(huán)
students [0] = s1;
students [1] = s2;
students [2] = s3;
students [3] = s4;
students [4] = s5;
//遍歷數(shù)組
for (int i = 0; i < students.length; i++) {
System.out.println(students[i]); //因為學(xué)生類中重寫了toString方法,可以直接輸出
Student s = students[i];//也可以通過創(chuàng)建對象調(diào)用get輸出
System.out.println(s.getName()+s.getAge());
}
}
}
package Array;
public class Student {
//成員變量姓名年齡
private String name;
private int age;
//構(gòu)造方法
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
//成員方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
Day15
集合
只用于存儲對象揍鸟,可以存儲不同類型的對象兄裂,長度可以變化
集合和數(shù)組的區(qū)別
長度區(qū)別
數(shù)組的長度固定
集合長度可變
內(nèi)容不同
數(shù)組存儲的是同一種類型的元素
而集合可以存儲不同類型的元素
元素的數(shù)據(jù)類型問題
數(shù)組可以存儲基本數(shù)據(jù)類型句旱,也可以存儲引用數(shù)據(jù)類型
集合只能存儲引用類型
Collection
Collection
List Set
ArrayList Vector LinkedList HashSet TreeSet
是集合的頂層接口阳藻,它的子體系有重復(fù)的,有唯一的谈撒,有有序的腥泥,有無序的
Collection的功能概述:
添加功能
boolean add(Object obj):添加一個元素
boolean addAll(Collection c):添加一個集合的元素
刪除功能
void clear():移除所有元素
boolean remove(Object o):移除一個元素
boolean removeAll(Collection c):移除一個集合的元素,移除一個就是移除
判斷功能
boolean contains(Object o):判斷集合中是否包含指定的元素
boolean containsAll(Collection c):判斷集合中是否包含指定的集合元素,只有包含所有的元素才叫包含
boolean isEmpty():判斷集合是否為空
獲取功能
Iterator<E> iterator()(重點)
長度功能
int size():元素的個數(shù)
交集功能
boolean retainAll(Collection c):兩個集合都有的元素啃匿,例A集合調(diào)用方法對B集合做交集蛔外,最終的結(jié)果放在A集合中,B不變溯乒,返回的布爾值代表集合A是否發(fā)生改變
把集合轉(zhuǎn)換為數(shù)組
Object[] toArray()
面試題:數(shù)組有沒有l(wèi)ength()方法呢?字符串有沒有l(wèi)ength()方法呢?集合有沒有l(wèi)ength()方法呢?
數(shù)組沒有l(wèi)ength()方法夹厌,有l(wèi)ength屬性,String有l(wèi)ength()方法裆悄,集合的是size()方法表示元素個數(shù)
public class CollectionDemo {
public static void main(String[] args) {
// 測試不帶All的方法
// 創(chuàng)建集合對象
// Collection c = new Collection(); //錯誤矛纹,因為接口不能實例化
Collection c = new ArrayList();
// boolean add(Object obj):添加一個元素
// System.out.println("add:"+c.add("hello"));
c.add("hello");
c.add("world");
c.add("java");
// void clear():移除所有元素
// c.clear();
// boolean remove(Object o):移除一個元素
// System.out.println("remove:" + c.remove("hello"));
// System.out.println("remove:" + c.remove("javaee"));
// boolean contains(Object o):判斷集合中是否包含指定的元素
// System.out.println("contains:"+c.contains("hello"));
// System.out.println("contains:"+c.contains("android"));
// boolean isEmpty():判斷集合是否為空
// System.out.println("isEmpty:"+c.isEmpty());
//int size():元素的個數(shù)
System.out.println("size:"+c.size());
System.out.println("c:" + c);
}
}
Object[] toArray()集合的遍歷
/*遍歷集合。以及輸出每個元素的長度
* */
import java.util.ArrayList;
import java.util.Collection;
public class CollectionDemo{
public static void main(String[] args) {
//創(chuàng)建集合對象
Collection c = new ArrayList();
//添加元素
c.add("hello");
c.add("world");
c.add("世界光稼,你好");
//不會集合的遍歷或南,但是集合有個功能Object[] toArray()將集合轉(zhuǎn)換為字符串
Object[] obj = c.toArray();
//對數(shù)組obj進行遍歷
for (int i = 0; i < obj.length; i++) {
//System.out.println(obj[i]+" ");
//每個元素的長度,就是字符串的長度艾君,length采够,但是obj沒有l(wèi)ength方法,所以向下轉(zhuǎn)型
String s = (String) (obj[i]);
System.out.println(s+"-----"+s.length());
}
}
}
Iterator iterator():迭代器冰垄,集合的專用遍歷方式
Object next():獲取元素,并移動到下一個位置
NoSuchElementException:沒有這樣的元素蹬癌,因為你已經(jīng)找到最后了
boolean hasNext():如果仍有元素可以迭代,則返回 true
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class CollectionDemo{
public static void main(String[] args) {
//創(chuàng)建集合對象
Collection c1 = new ArrayList();
//創(chuàng)建學(xué)生對象
Student s1 = new Student("張三",15);
Student s2 = new Student("李四",15);
Student s3 = new Student("王六",14);
//添加元素
c1.add(s1);
c1.add(s2);
c1.add(s3);
//Iterator iterator():迭代器虹茶,集合的專用遍歷方式
Iterator it = c1.iterator();
//Object next():獲取元素,并移動到下一個位置
System.out.println(it.next());
System.out.println(it.next());
System.out.println(it.next());
//System.out.println(it.next());
// NoSuchElementException沒有這樣的元素異常冀瓦,因為就三個元素,不能輸出第四個
// boolean hasNext():如果仍有元素可以迭代写烤,則返回 true
while(it.hasNext()){
//System.out.println(it.next());
String s = (String) it.next();
System.out.println(s);
}
//while循環(huán)可以用for改進翼闽,把創(chuàng)建迭代器對象放在第一條語句中,條件是it.hasNext()洲炊,省略第三句感局,
//只判斷第二句是否成立尼啡,這樣的好處是for運行完Iterator對象it就是垃圾,可以被回收询微,提高了效率
for (Iterator it = c1.iterator();it.hasNext();) {
Student s = (Student) it.next();
System.out.println(s.getName()+s.getAge());
}
}
}
集合的使用步驟
創(chuàng)建集合對象
Collection c1 = new ArrayList();
創(chuàng)建元素對象
Student s1 = new Student("張三", 15);//以學(xué)生類為例
把元素添加到集合
c1.add(s1);
遍歷集合
通過集合對象獲取迭代器對象
Iterator it = c1.iterator();
通過迭代器對象的hasNext()方法判斷是否有元素
it.hasNext();//返回布爾值崖瞭,有下一個元素就是true
通過迭代器對象的next()方法獲取元素并移動到下一個位置
Student s = (Student) it.next();//一般是向下轉(zhuǎn)型成為學(xué)生類對象
System.out.println(s.getName()+s.getAge());//調(diào)用學(xué)生類的方法輸出,可以單獨輸出
List接口
有序的 collection(也稱為序列),此接口的用戶可以對列表中每個元素的插入位置進行精確地控制,用戶可以根據(jù)元素的整數(shù)索引(在列表中的位置)訪問元素,并搜索列表中的元素,與 set 不同撑毛,列表通常允許重復(fù)的元素
List集合
特點:有序(存儲和取出的元素一致)书聚,可重復(fù)的
public class ListDemo2 {
public static void main(String[] args) {
// 創(chuàng)建集合對象
List list = new ArrayList();
// 存儲元素
list.add("hello");
list.add("world");
list.add("java");
list.add("javaee");
list.add("android");
list.add("javaee"); //可重復(fù)的
list.add("android");
// 遍歷集合
Iterator it = list.iterator();
while (it.hasNext()) {
String s = (String) it.next();
System.out.println(s); //輸出順序跟定義順序一致
}
}
}
List集合的特有功能:
添加功能
void add(int index,Object element):在指定位置添加元素
獲取功能
Object get(int index):獲取指定位置的元素
列表迭代器
ListIterator listIterator():List集合特有的迭代器
刪除功能
Object remove(int index):根據(jù)索引刪除元素,返回被刪除的元素
修改功能
Object set(int index,Object element):根據(jù)索引修改元素,返回被修飾的元素
List集合特有的遍歷方法(通過size()和gat()結(jié)合)
import java.util.ArrayList;
import java.util.List;
public class CollectionDemo {
public static void main(String[] args) {
//創(chuàng)建集合對象
List li = new ArrayList();
//創(chuàng)建學(xué)生對象
Student s1 = new Student("張三",15);
Student s2 = new Student("李四",15);
Student s3 = new Student("王五",16);
//將學(xué)生對象添加到集合中
li.add(s1);
li.add(s2);
li.add(s3);
//遍歷集合
for (int i = 0; i < li.size(); i++) {
//System.out.println(li.get(i)); //可以遍歷但不推薦藻雌,需要重寫toString方法且不靈活
Student s = (Student) li.get(i);
System.out.println(s.getName()+s.getAge());
}
}
}
列表迭代器:
ListIterator listIterator():List集合特有的迭代器雌续,該迭代器繼承了Iterator迭代器,所以胯杭,就可以直接使用hasNext()和next()方法
特有功能:
Object previous():獲取上一個元素
boolean hasPrevious():判斷是否有元素
注意:ListIterator可以實現(xiàn)逆向遍歷驯杜,但是必須先正向遍歷,才能逆向遍歷做个,所以一般無意義鸽心,不使用
public class ListIteratorDemo {
public static void main(String[] args) {
// 創(chuàng)建List集合對象
List list = new ArrayList();
list.add("hello");
list.add("world");
list.add("java");
// ListIterator listIterator()
ListIterator lit = list.listIterator(); // 子類對象
// while (lit.hasNext()) {
// String s = (String) lit.next();
// System.out.println(s);
// }
// System.out.println("-----------------");
// System.out.println(lit.previous());
// System.out.println(lit.previous());
// System.out.println(lit.previous());
// NoSuchElementException
// System.out.println(lit.previous());
while (lit.hasPrevious()) {
String s = (String) lit.previous();
System.out.println(s);
}
System.out.println("-----------------");
// 迭代器
Iterator it = list.iterator();
while (it.hasNext()) {
String s = (String) it.next();
System.out.println(s);
}
System.out.println("-----------------");
}
}
ConcurrentModificationException
當(dāng)方法檢測到對象的并發(fā)修改,但不允許這種修改時居暖,拋出此異常
產(chǎn)生的原因:
迭代器是依賴于集合而存在的顽频,在判斷成功后,集合的中新添加了元素太闺,而迭代器卻不知道糯景,所以就報錯了,這個錯叫并發(fā)修改異常
解決方法
迭代器迭代元素跟束,迭代器修改元素,元素是跟在剛才迭代的元素后面的
// 方式1:迭代器迭代元素莺奸,迭代器修改元素
// 而Iterator迭代器卻沒有添加功能,所以我們使用其子接口ListIterator
ListIterator lit = list.listIterator();
while (lit.hasNext()) {
String s = (String) lit.next();
if ("world".equals(s)) {
lit.add("javaee");
}
}
集合遍歷元素冀宴,集合修改元素(普通for),元素在最后添加的
// 方式2:集合遍歷元素灭贷,集合修改元素(普通for)
for (int x = 0; x < list.size(); x++) {
String s = (String) list.get(x);
if ("world".equals(s)) {
ist.add("javaee");
}
}
常見的數(shù)據(jù)結(jié)構(gòu)
棧:先進后出 例:子彈夾
隊列:先進先出 例:超市排隊結(jié)賬
數(shù)組:存儲同一種類型多個元素的容器,有索引,方便獲取,特點:查詢快,增刪慢
鏈表:由一個鏈子把多個結(jié)點連接起來組成的數(shù)據(jù),結(jié)點由數(shù)據(jù)和地址組成,特點:查詢慢,增刪快
List子類的特點
ArrayList:
底層數(shù)據(jù)結(jié)構(gòu)是數(shù)組,查詢快略贮,增刪慢
線程不安全甚疟,效率高
Vector:
底層數(shù)據(jù)結(jié)構(gòu)是數(shù)組,查詢快逃延,增刪慢
線程安全览妖,效率低
LinkedList:
底層數(shù)據(jù)結(jié)構(gòu)是鏈表,查詢慢揽祥,增刪快
線程不安全讽膏,效率高
List的三個子類要用哪一個
要安全嗎
要:Vector(即使要安全,也不用這個了拄丰,后面有替代的)
不要:ArrayList或者LinkedList
查詢多:ArrayList
增刪多:LinkedList