java
一、java 基本介绍
1.注释
单行注释
多行注释
/* 遇到最近的*/
中间的所有内容会被注释文档注释
/** 内容*/
2.在java中创建类
在java中所有的存在都是以类的方式存在
文件名和类名必须一致
主方法是程序的入口,在java中必须有主方法,没有主方法将不能运行
所有的符号都是英文的,每一个语句必须以分号结束
public – 公有 static – 静态 void – 返回值类型是空
main – 主函数名字
String[] agrs – String
args – 参数的名字
class Demo{
public static void main(string[] args){
System.out.println("hello world")
}
}
3. println 和 print 的区别
System.out.println(“hello world”) – 自动换行
System.out.print(“hello world”) – 不会自动换行
二、java 数据类型
非数值类型
- 一个是逻辑的布尔 boolean
- 一个是字符 char
数字类型
- 整数:byte --一个字节、short – 两个字节、int – 四个字节、 long – 8个字节
- 小数:float – 单精度 四个字节、double – 双精度 八个字节
三、变量
必须先声明变量类型
定义格式: 变量类型 变量名=值;
整数 2 默认的类型是int
小数 1.2 默认的类型是double
package com.qf;
public class BianLiang {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* java中定义一个变量
* 必须声明类型
* 变量类型 变量名字=值;
* 整数 2 默认的类型是int
* 小数 1.2 默认的类型是double
*/
byte b = 120;
System.out.println("b="+b);
short s = 120;
System.out.println("s="+s);
int i = 120;
System.out.println("i="+i);
long l = 120;
System.out.println("l="+l);
float f1 = 1.2f;
System.out.println("f1="+f1);
double d1 = 1.2;
System.out.println("d1"+d1);
System.out.println("+++++++++++++非数字类型==============");
char c1 = 'a';
System.out.println("c1="+c1);
c1 = '行';
System.out.println("c1="+c1);
boolean b1 = true;
System.out.println("b1="+b1);
b1 = false;
System.out.println("b1="+b1);
}
}
四、类型转换
数字类型 byte、short、int、long 互相可以转换
小转大自然转,大转小强制转换(高位会丢失)
package com.qf;
public class LeiXingZhuanHuan {
public static void main(String[] args) {
// TODO Auto-generated method stub
// 数字类型 byte short int long
//小转大 自然转
//大转小 强制类型转换
byte a = 10;
System.out.println("a="+a);
int x = a;
System.out.println("x="+x);
System.out.println("++++++++++++++大---小++++++++++++++++");
int a1 = 128;
System.out.println("a1="+a1);
// 0000 0000 0000 0000 0000 000 1000 0000
byte x1 = (byte) a1;
//1000 0000----
//0111 1111 +1=128
//-128
System.out.println("x1="+x1);
System.out.println("++++++++++++++++++++++");
char c='行';
System.out.println("c="+c);
int cc = c;
System.out.println("cc="+cc);//cc=34892
int cc2 = 34893;
char c2 = (char) cc2;
System.out.println("34893---"+c2);
}
}
五、转义字符
\n --换行符
\t --制表符(table键)
package com.qf;
public class ZhuanYi {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("hello \n world");
System.out.print("killer");
System.out.print(" is comming");
System.out.println();
System.out.println("关羽\t张飞\t刘备");
}
}
六、运算符
1.算数运算符
+、-、*、/、%、++、--、
a++
– 先运算再自增++a
– 先自增,再运算
a--
– 先运算再自减--a
– 先自减,再运算a = a+10可以简写为 a += 10
package com.yunsuanfu;
public class SuanShu {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a=1,b=2,c=3;
System.out.println("a="+a+" b="+b+" c="+c);
System.out.println("a+b="+(a+b));
System.out.println("a-b="+(a-b));
System.out.println("a*b="+(a*b));
System.out.println("a/b="+(a/b));
System.out.println("a%b="+(a%b));
System.out.println("++++++++++++++++++++");
a++;
System.out.println("a="+a);
++a;
System.out.println("a="+a);
a--;
System.out.println("a="+a);
--a;
System.out.println("a="+a);
System.out.println("=====参与运算的时候的区别======");
System.out.println("====a++先参与运算 后自增======");
System.out.println("====++a先自增 后参与运算====");
int x=2;
int y = 2+3*x++;//2+3*2
System.out.println("x="+x+" y="+y);//x=3 y=8
int x2=2;
int y2 = 2+3*++x2;//2+3*3
System.out.println("x2="+x2+" y2="+y2);//x2=3 y2=11
}
}
package com.yunsuanfu;
public class ZuHe {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a= 10;
System.out.println("a="+a);
a += 10;
System.out.println("a="+a);
}
}
2.三目运算符
eg:int y = x>0?10:-10
-----条件真取前面,条件假取后面
package com.yunsuanfu;
public class SanMu {
public static void main(String[] args) {
// TODO Auto-generated method stub
int x= -2;
int y = x>0?10:-10;//条件是真取前面 否则取后面
System.out.println("x="+x+" y="+y);
}
}
七、流程控制语句
1.if else
package com.qf.liucheng;
public class IfDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a = 10;
if (a>5) {
System.out.println("a是一个大于5的数");
}
boolean isRain=false;
if (isRain) {
System.out.println("====下雨了====");
} else {
System.out.println("====没下雨=====");
}
}
}
2.if else 的嵌套
package com.qf.liucheng;
public class IfElse {
public static void main(String[] args) {
// TODO Auto-generated method stub
//90 A 80 B 70 C 60 D 不及格
//0--100
int chengJi=18;
//判断有效范围
if (chengJi >= 0 && chengJi<=100 ) {
if (chengJi>=90) {
System.out.println("A");
}else if (chengJi>=80) {
System.out.println("B");
}else if (chengJi>=70) {
System.out.println("C");
}else if (chengJi>=60) {
System.out.println("D");
}else {
System.out.println("不及格");
}
} else {
System.out.println("===无效成绩===");
}
}
}
3.swith case default
3.1 练习1
package com.qf.liucheng;
public class SwitchDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("====switch语句碰到break结束 或者大括号自然结束");
int day=2;
switch (day) {
case 1:
System.out.println("星期一");
break;
case 2:
System.out.println("星期2");
break;
case 3:
System.out.println("星期三");
break;
case 4:
System.out.println("星期四");
break;
case 5:
System.out.println("星期五");
break;
case 6:
System.out.println("星期六");
break;
case 7:
System.out.println("星期天");
break;
default:
System.out.println("===上面都不是 无效值===");
break;
}
}
}
3.2 练习2:结果相同可以合并
package com.qf.liucheng;
public class SwitchDemo2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int yue=10;
switch (yue) {
case 1:
case 2:
case 3:
System.out.println("===这是春天=====");
break;
case 4:
case 5:
case 6:
System.out.println("===这是夏天=====");
break;
case 7:
case 8:
case 9:
System.out.println("===这是秋天=====");
break;
case 10:
case 11:
case 12:
System.out.println("===这是冬天=====");
break;
default:
System.out.println("===这是一个无效的月份===");
break;
}
}
}
4.while语句
package com.qf.liucheng;
public class WhileDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
//遍历1-5
int i=1;
while (i<=5) {
System.out.print(i+",");
i++;
}
System.out.println();
System.out.println("=====求1--100之间偶数的和====");
i = 1;
int sum=0;
while (i<=100) {
if (i%2 == 0) {
sum +=i;
}
i++;
}
System.out.println("1--100之间偶数的和="+sum);
i = 2;
sum =0;
while (i<=100) {
sum+=i;
i+=2;
}
System.out.println("1--100之间偶数的和="+sum);
}
}
5.do while语句
package com.qf.liucheng;
public class DoWhile {
public static void main(String[] args) {
// TODO Auto-generated method stub
//遍历1--5 dowhile---只有第一次不判断直接 后面都是先判断后执行
int i=1;
do {
System.out.print(i+",");
i++;
} while (i<=5);
System.out.println("=======1--100之间奇数的和=========");
int j = 1;
int sum=0;
do {
if (j%2 != 0) {
sum+=j;
}
j++;
} while (j<=100);
System.out.println("1--100之间奇数的和="+sum);
j=1;
sum=0;
do {
sum += j;
j += 2;
} while (j<=100);
System.out.println("1--100之间奇数的和="+sum);
}
}
6.for 语句
for(初始化语句;条件语句;变化语句){
}
package com.qf.liucheng;
public class ForDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
//for循环 初始化语句 条件语句 变化语句
for (int i = 1; i <= 5; i++) {
System.out.print(i+",");
}
System.out.println();
System.err.println("++++++++++这是一个错误++++++++++++");
int sum = 0;
for (int i = 1; i < 101; i++) {
if (i % 2 != 0) {
sum += i;
}
}
System.out.println("1==100之间奇数的和="+sum);
sum = 0;
for (int i = 1; i < 101; i+=2) {
sum+=i;
}
System.out.println("1==100之间奇数的和="+sum);
}
}
7.循环之间的区别
while – 每次判断条件 直到条件不符合结束
do while – 无论如何先执行一次 后面每次先判断后执行 – 有些代码必须至少执行一次 优先选择do while
for – 变量定义声明周期短 省内存 for循环的变量只在循环中有效 除了循环就会被释放
package com.qf.liucheng;
public class XunHuanQubie {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* while---每次判断条件 直到条件不符合结束
* do--while 无论如何先执行一次 后面每次先判断 后执行 ---- 有些代码必须至少执行一次 优先选择dowhile
* for----变量定义声明周期短 省内存 for循环的变量只在循环中有效出了循环就会被释放
*/
do {
System.out.println("===至少执行一次====");
} while (false);
System.out.println("++++++++++++++++++++++");
boolean isZhen=false;
while (isZhen) {
System.out.println("======");
}
int x =8;
while (x<=100) {
System.out.print(x+",");
x++;
}
System.out.println();
System.out.println(x);
for (int i = 0; i < 100; i++) {
System.out.print(i+",");
}
System.out.println();
//System.out.println(i);
}
}
八、循环的嵌套
1.while嵌套
package com.qf.qiantao;
public class QianTao001 {
//语句除了声明语句外 一般都在方法内
public static void main(String[] args) {
// TODO Auto-generated method stub
int i=1;
while (i<=3) {
int j=1;
while (j<=3) {
System.out.print(i+"---"+j+"\t");
j++;
}
i++;
System.out.println();
}
System.out.println("++++++++++++++++++++++++++");
for (int j = 1; j <= 3; j++) {
for (int j2 = 1; j2 <= 3; j2++) {
System.out.print(j+"---"+j2+"\t");
}
System.out.println();
}
}
}
2.嵌套练习
2.1 练习1
package com.qf.qiantao;
public class QianTao2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
*/
for (int i = 1; i < 6; i++) {
for (int j = 1; j < 6; j++) {
System.out.print("* ");
}
System.out.println();
}
System.out.println("+++++++++++++++++++++++++++++++=");
/*
* * * * *
* * * *
* * *
* *
*
*/
for (int i = 1; i < 6; i++) {
for (int j = 1; j <= 6-i; j++) {
System.out.print("* ");
}
System.out.println();
}
System.out.println("+++++++++++++++++++++++++++++++=");
/*
*
*
* *
* * *
* * * *
* * * * *
*/
for (int i = 1; i < 6; i++) {
for (int j = 1; j <=i ; j++) {
System.out.print("* ");
}
System.out.println();
}
/*
1
12
123
1234
12345
*/
for (int i = 1; i < 6; i++) {
for (int j = 1; j <=i ; j++) {
System.out.print(j);
}
System.out.println();
}
System.out.println("+++++++++++++++++++++++++++++++=");
/*
* 2*3=6
*/
for (int i = 1; i <= 9; i++) {
for (int j = 1; j < i+1; j++) {
System.out.print(j+"*"+i+"="+(i*j)+"\t");
}
System.out.println();
}
}
}
2.2 练习2
package com.qf.qiantao;
public class QianTao3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
*
**
***
****
*****
****
***
**
*
*/ for (int i = 1; i < 10; i++) {
if (i<=5) {//上半部分
for (int j = 1; j < 6; j++) {
if (j>=6-i) {
System.out.print("* ");
} else {
System.out.print(" ");
}
}
} else {//下半部分
for (int j = 1; j < 6; j++) {
if (j>=i-4) {
System.out.print("* ");
} else {
System.out.print(" ");
}
}
}
System.out.println();
}
/*
*
1 1 1
2 2 2
3 3 3 3 3
4 4 4
5 5 5
*
*/
System.out.println("+++++++++++++++++++++++++++++");
for (int i = 1; i < 6; i++) {
for (int j = 1; j <6; j++) {
if (i==3||j==3||j==5||(j==1&&(i==1||i==5))||(j==2&&(i==2||i==4))) {
System.out.print(i+" ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
System.out.println("++++++++++++++++++++++++++++++++++++");
//求100以内的质数
for (int i = 2; i < 101; i++) {
//判断i是不是质数
boolean isZhi=true;
for (int j = 2; j < i; j++) {
if (i%j==0) {
isZhi = false;
break;//后面的数字就不用判断了
}
}
if (isZhi) {
System.out.print(i+",");
}
}
System.out.println();
System.out.println("++++++++++++++++++++++++++++++");
/*
* 一个数如果恰好等于它的因子之和,这个数就称为 "完数 "。例如6=1+2+3.
编程 找出1000以内的所有完数。
*/
for (int i = 2; i < 1000; i++) {
//定义一个因子之和
int sumYinZi=0;
for (int j = 1; j < i; j++) {
if (i%j==0) {//说明j是i的因子
if (i==496) {
System.out.print(j+"---");
}
sumYinZi +=j;
}
}
if (i == sumYinZi) {
System.out.print(i+",");
}
}
System.out.println();
}
}
4.循环的中断
break – 直接中断循环
continue – 只中断一次循环
package com.qf.qiantao;
public class ZhongDuan {
public static void main(String[] args) {
// TODO Auto-generated method stub
//break--_直接中断循环
//continue---只中断一次 继续循环
for (int i = 0; i < 6; i++) {
if (i==3) {
break;
}
System.out.println(i+"---");
}
System.out.println("+++++++++++++++++++++");
for (int i = 0; i < 6; i++) {
if (i==3) {
continue;
}
System.out.println(i+"---");
}
System.out.println("++++++++++++++++++++++++++=");
QQ:for (int i = 1; i < 6; i++) {
for (int j = 1; j < 6; j++) {
if (i==3) {
break QQ;//在java中可以中断外面的循环
}
System.out.print("*");
}
System.out.println();
}
}
}
九、函数
方法一定在一个类当中,方法和方法是并列关系,函数里面不能定义函数
- 有没有参数,有几个,什么类型
- 有没有返回值,返回值的类型是什么
1.函数调用
package com.qf.hanshu;
public class FunDemo1 {
//方法一定在一个类当中
//方法和方法是并列关系 java里面 函数里面不能定义函数
public static void main(String[] args) {
// TODO Auto-generated method stub
int jieguo = oneAndOne();//使用jieguo来接收方法的返回值
System.out.println(jieguo);
int jieguo2 = fun2(10);//alt+shift+L
System.out.println(jieguo2);
System.out.println("+++++++++++++++++");
int intAndInt = intAndInt(2, 8);
System.out.println(intAndInt);
System.out.println("+++++++++++++++++++++++");
printTriangle(4);
System.out.println("++++++++++++++++");
int sum = getSum(10);
System.out.println(sum);
System.out.println("+++++++++++++++++");
long jieCheng = jieCheng(5);
System.out.println(jieCheng);
long jieCheng2 = jieCheng(13);
System.out.println(jieCheng2);
}
/*
* 01--1+1
打印方法
一个数的三倍加1
两个int之和
打印一个任意大小的等边三角形
打印任意大小的菱形
求1---n之间的和
求一个整数的阶乘
*/
//求一个整数的阶乘
//有没有参数 int a
// 有返回值 一般要写出long
public static long jieCheng(int a) {
long jc=1;
for (int i = 1; i < a+1; i++) {
jc *= i;
}
return jc;
}
//求1---n之间的和
//一个参数 int n
//返回值int
public static int getSum(int n) {
int sum=0;
for (int i = 1; i < n+1; i++) {
sum += i;
}
return sum;
}
//打印一个任意大小的等边三角形
//有一个参数 是边的星星的数量
//没有返回值 void--占位符 意思是这个函数没有返回值
public static void printTriangle(int a) {
/*
*
*
* *
* * *
* * * *
* * * * *
*/
for (int i = 1; i < a+1; i++) {
for (int j = 1; j < a+1; j++) {
if (j>=a+1-i) {
System.out.print("* ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
//两个int之和
//1:有两个参数 int a int b
//2:有返回值 a+b
public static int intAndInt(int a,int b) {
return a+b;
}
//一个数的三倍加1
//有没有参数 有一个数 int i
//有没有返回值 int 3*i+1
public static int fun2(int i) {
return 3*i+1;
}
//有没有参数 有几个 分别是什么类型
//有没有返回值 返回值的类型是什么
public static int oneAndOne() {
return 1+1;
}
}
package com.qf.hanshu;
public class FunDemo2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("++++++++++++++++++++++++=");
for (int i = 2; i < 101; i++) {
System.out.println(i+"是质数吗?"+isZhiShu(i));
}
System.out.println("++++++++++++++++++++++");
int zhiCount = getZhiCount(100);
System.out.println(zhiCount);
}
/*
* 写一个方法判断一个数是不是质数
*/
//有没有返回值 有 boolean
//有 一个数 int
public static boolean isZhiShu(int a) {
for (int i = 2; i < a; i++) {
if (a % i == 0) {
return false;//有一个除尽 就说明不是了
}
}
return true;//出了循环 还没返回 说明都没除尽 说明是质数
}
/*
* 写一个方法 求2---n之间的质数的数量
*/
//参数 int n
//返回值 int count
public static int getZhiCount(int n) {
int count = 0;
for (int i = 2; i < n+1; i++) {
if (isZhiShu(i)) {
count++;
}
}
return count;
}
}
2.函数重载
方法名称相同,参数不同
package com.qf.hanshu;
public class ChongZai {
public static void main(String[] args) {
// TODO Auto-generated method stub
byte a=9;
int b = 10;
System.out.println("++++0+++++++++++++");
add(a, b);
System.out.println("++++1+++++++++++++");
add(a, a);
System.out.println("++++2+++++++++++++");
add(b, a);
System.out.println("++++3+++++++++++++");
add(b, b);
}
//函数名相同 参数列表不同的函数
//写一个方法 求两个数之和
public static long add(byte a,byte b) {
System.out.println("=====byte==and===byte===");
return a+b;
}
/*public static int add(int a,int b) {
return a+b;
}不允许同名而且参数类型数目完全一样,只有返回值不同*/
public static long add(byte a,int b) {
System.out.println("=====byte==and===int===");
return a+b;
}
public static long add(int a,byte b) {
System.out.println("=====int==and===byte===");
return a+b;
}
public static long add(int a,int b) {
System.out.println("=====int==and===int===");
return a+b;
}
public static long add(int a,int b,int c) {
return a+b+c;
}
}
3.递归函数
package com.qf.hanshu;
public class DiGui {
public static void main(String[] args) {
// TODO Auto-generated method stub
long jieCheng = jieCheng(5);
System.out.println(jieCheng);
for (int i = 1; i < 11; i++) {
int fbnq = getFbnq(i);
System.out.println(fbnq);
}
}
//斐波那契数列
//兔子问题
// 1 1 2 3 5 8 13 21 34 55
// f(n) = f(n-1)+f(n-2)
// 规律里面两个未知 说明出口也是两个
// f(1)=1 f(2)=1
public static int getFbnq(int n) {
if (n==1 || n==2) {
return 1;
}
return getFbnq(n-1)+getFbnq(n-2);
}
//阶乘
//f(n) = n * f(n-1)
//.....3.2.1 1!=1
//写递归 一般先找到出口
//再找到规律
public static long jieCheng(int n) {
//出口是1
if (n==1) {
return 1;
}
return n * jieCheng(n-1);
}
}
十、数组
元素类型[ ] 数组名 = new 元素类型[数组长度]
1.数组的创建和遍历
常见异常:
- 数组下标越界异常
- arr2 = null 打印时会出现空指针异常
package com.qf.shuzu;
public class ChuangJian {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* //如果数组的值预先知道 我们就可以使用静态初始化
//如果这些值不确定,就应该选择使用动态初始化
*/
int[] arr1 = new int[5];//创建了一个长度是5的int数组
//这个数组里面存放的只能是int类型 5---长度是
//5---4个字节
System.out.println(arr1);//[I@659e0bfd [---数组 I==int @---连接符 659e0bfd--地址
float[] cs = new float[5];
System.out.println(cs);//[F@2a139a55
System.out.println(arr1.length);
//以下标的形式来访问
//0---len-1
System.out.println(arr1[1]);
System.out.println(cs[1]);
arr1[0] = 9;
System.out.println(arr1[0]);
arr1[3] = 88;
System.out.println("++++++++++静态定义+++++++++++++++");
int[] arr2 = {10,29,30,40,80};
System.out.println(arr2);
System.out.println(arr2[2]);
System.out.println("+++=下标遍历====");
for (int i = 0; i < arr2.length; i++) {
System.out.print(arr2[i]+",");
}
System.out.println();
System.out.println("++++++++for each++++++++");
for (int i : arr2) {
System.out.print(i+",");
}
System.out.println();
System.out.println("+++++++++++++");
System.out.println("++++++++++++数组下标越界异常=====");
//arr2[10] = 88;//Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
arr2 = null;
System.out.println("+++++++++空指针异常++++++");
System.out.println(arr2.length);//Exception in thread "main" java.lang.NullPointerException
}
}
2.数组遍历的方法
package com.qf.shuzu;
public class ShuZuBianLi {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr1 = {100,2,3,40,80,80};
bianLi(arr1);
System.out.println("+++++++++++++++++");
bianli2(arr1);
System.out.println("++++++++++++++++++++");
char[] cs = {'名','a','1','K','*'};
bianli3(cs );
System.out.println("++++++++++");
int maxInArr = getMaxInArr(arr1);
System.out.println(maxInArr);
}
//写一个方法求一个值在一个int数组的位置 找不到的时候返回-1
//参数 int[] arr int key
public static int getKeyIndexInArr(int[] arr,int key) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == key){
return i;
}
}
return -1;
}
//写一个方法求一个int数组中的最大值
//int[]
//int
public static int getMaxInArr(int[] arr) {
int max=arr[0];
for (int i : arr) {
if (i > max) {
max = i;
}
}
return max;
}
//写一个方法对一个字符数组进行遍历
public static void bianli3(char[] cs) {
for (char c : cs) {
System.out.print(c+",");
}
System.out.println();
}
//写一个方法对一个int数组进行遍历
//int[]
public static void bianLi(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+",");
}
System.out.println();
}
//写一个foeach的遍历
public static void bianli2(int[] arr) {
for (int i : arr) {
System.out.print(i+",");
}
System.out.println();
}
}
3.数组的排序
package com.qf.shuzu;
public class SortDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = {10,8,20,399,20,9};
maopaoSort(arr);
System.out.println("+++++++++++++++++++++++++++++");
int[] arr2={100,29,30,28,30,120,888};
xuanZeSort(arr2);
System.out.println("++++++++++++++++");
bianLi(arr2);
huan(arr2, 1,5);
bianLi(arr2);
System.out.println("+++++++++++++++++");
}
public static void bianLi(int[] arr) {
for (int i : arr) {
System.out.print(i+",");
}
System.out.println();
}
//写一个方法对一个int数组进行冒泡排序
/*
* 冒泡排序
相邻元素比较,将大的放到后面,直到数组成为一个有序数组
外循环控制的是第几次比较
内循环控制每次比较过程,谁跟谁比
*/
public static void maopaoSort(int[] 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 temp = arr[j];
arr[j]= arr[j+1];
arr[j+1] = temp;*/
huan(arr, j, j+1);
}
}
bianLi(arr);
}
}
/*
* 选择排序
* 选定一个位置 将最小值放到这个位置
*
*/
public static void xuanZeSort(int[] arr) {
//先写外循环 选定位置
for (int i = 0; i < arr.length-1; i++) {
//从选定位置的下一个开始进行比较
for (int j = i+1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
/*int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;*/
huan(arr, i, j);
}
}
bianLi(arr);
}
}
//写一个方法来对一个int数组的两个位置的值进行交换
//参数 int【】 arr i j
public static void huan(int[] arr,int i,int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
4.折半查找 — 前提是数组有序
package com.qf.shuzu;
public class ZheBan {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = {1,20,30,33,39,79,300,389,890};
int keyInSortArr = getKeyInSortArr(arr, 389);
System.out.println(keyInSortArr);
}
//折半查找
//在一个有序的列表中一个值的位置
// min max mid
//mid key 大于 小于 等于
public static int getKeyInSortArr(int[] arr,int key) {
int min=0;
int max = arr.length-1;
int mid=0;
while (min <= max) {
mid = (min+max)/2;
if (arr[mid] > key) {//说明key在左面 缩小右边界
max = mid-1;
}else if (arr[mid] < key) {//说明key在右面 放大左边界
min = mid+1;
}else {
return mid;
}
}
return -1;//说明没有找到
}
}
5.二维数组
package com.qf.shuzu;
public class ErWei {
public static void main(String[] args) {
// TODO Auto-generated method stub
//二维数组
int[][] arr = new int[2][3];//2---它有几个子数组 3--表示字数组的长度
int[] zi1={1,2,3};
int[] zi2 = {11,22,33};
System.out.println(arr);//[[I@659e0bfd [[--二维数组 I 元素是int类型
arr[0] = zi1;
arr[1] = zi2;
System.out.println(arr[0]);//[I@2a139a55
System.out.println(arr[1]);//[I@15db9742
System.out.println(arr[1][1]);
System.out.println(arr[1][0]);
System.out.println("+++++++++++++++++++++++");
for (int i = 0; i < arr.length; i++) {
//arr[i]
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + ",");
}
System.out.println();
}
System.out.println("+++++++++++++++++++++++++");
for (int[] i : arr) {
for (int j : i) {
System.out.print(j+",");
}
System.out.println();
}
System.out.println("+++++++++++++++++++++");
int[][] arr2 = {{1,2,3},{99},{10,12,13}};
System.out.println(arr2[0].length);
System.out.println(arr2[1].length);
System.out.println(arr2[2].length);
System.out.println("++++++++++++");
for (int[] is : arr2) {
for (int i : is) {
System.out.print(i+",");
}
System.out.println();
}
}
}
6.二维数组方法
package com.qf.shuzu;
public class ErWei2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
char[][] css = {{'a','K'},{'1','4','7'},{'汉','敏','贾'}};
bianLi(css);
System.out.println("+++++++++++++++++++");
int indexInErArr = getIndexInErArr(css, '敏');
System.out.println(indexInErArr);
}
//写一个方法 求一个值在一个二维数组的第几个子数组中
public static int getIndexInErArr(char[][] arr,char key) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] == key) {
return i+1;
}
}
}
return -1;
}
//定义一个方法 来遍历一个二维的字符数组
//char[][] arr
public static void bianLi(char[][] arr) {
for (char[] cs : arr) {
for (char c : cs) {
System.out.print(c+",");
}
System.out.println();
}
}
}
面向对象(封装+多态+继承)
一、封装
1.类的封装
狭义的封装就是私有属性,提供set和get方法
private:私有 – 类以外无法用
成员.属性
访问右击–source –
- using fields --构造函数
- getter – get方法
- tostring
1.1 封装
package good;
public class Good {
private String name;//成员变量
private int price;
public Good(String name, int price) {
super();
this.name = name;
this.price = price;
}
public Good() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public String toString() {
return "Good [name=" + name + ", price=" + price + "]";
}
}
1.2 调用
package usegood;
public class TestGood {
public static void main(String[] args) {
Good good1 = new Good();
Good good2 = new Good("苹果",10);
System.out.println(good2);
System.out.println(good2.getName());
good1.setName("香蕉");
good1.setPrice(11);
System.out.println(good1);
}
}
2.构造之间的调用
super和this调用函数 – 只能用一个
package com.qf.duixiang;
public class Person2 {
private String name;
private int age;
public Person2() {
super();
}
public Person2(String name) {
this();
this.name = name;
}
public Person2(String name, int age) {
//super();
//this.name = name;
this(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 "Person2 [name=" + name + ", age=" + age + "]";
}
//写一个方法 比较当前对象和另外一个人的年龄的大小 大了 1 等于 0 小于 -1
public int bijiaoAge(Person2 person) {
//this.age person.age
if (this.age > person.age) {
return 1;
}else if (this.age < person.age) {
return -1;
}
return 0;
}
}
package com.qf.test;
import com.qf.duixiang.Person2;
public class TestPerson2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Person2 person2=new Person2("关羽",32);
Person2 person22=new Person2("张飞", 26);
Person2 person23 = new Person2("刘备", 33);
System.out.println(person2.bijiaoAge(person22));
System.out.println(person2.bijiaoAge(person23));
Person2 person24 = new Person2("曹操", 33);
System.out.println(person23.bijiaoAge(person24));
}
}
3.静态变量
静态不能调用非静态,只能调用静态
static – 静态
静态的调用 – 可以直接用 类. 调用
什么时候使用静态
- 当所有的对象对应的这个成员变量值都相同时 定义为 static 变量
- 当一个方法不访问成员变量的时候可以定义为static – 工具类
package com.qf.duixiang;
public class Ren {
private String name;
private int age;
private static String guoJi="cn";//静态的成员变量---类变量
public Ren(String name, int age) {
super();
this.name = name;
this.age = age;
}
//静态方法 可以直接被类.调用
public static String getGuoJi() {
//this.age;静态环境不能调用this---静态不能调用非静态--静态存在的时间早 而非静态存在的时间晚
return guoJi;
}
public static void setGuoJi(String guoJi) {
Ren.guoJi = guoJi;
}
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 "Ren [name=" + name + ", age=" + age + "]";
}
}
package com.qf.test;
import com.qf.duixiang.Ren;
public class TestRen {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(Ren.getGuoJi());
Ren.setGuoJi("中国人");
System.out.println(Ren.getGuoJi());
Ren ren=new Ren("武松", 20);
System.out.println(ren);
//System.out.println(ren.getGuoJi());//在java中一般不使用对象直接调用静态 而使用类.
System.out.println(Ren.getGuoJi());
System.out.println("======静态只能调用静态====静态不能调用非静态======");
}
}
4.数组工具类(shuzutools)
工具类主要存在两种内容
一种是静态的常量,一种是静态的方法
final — 常量
4.1 shuzutools 类
package com.qf.tools;
public class ShuZuTools {
//工具类主要存在两种内容‘
//一种是静态的常量
//一种是静态方法
public static final double MATH_PI =3.14; //常量的特点是名字全是大写的 内容定义后永不更改
public static void bianLi(int[] arr) {
for (int i : arr) {
System.out.print(i+",");
}
System.out.println();
}
//求一个int数组的最大值
public static int getMaxInArr(int[] arr) {
int max= arr[0];
for (int i : arr) {
if (i>max) {
max = i;
}
}
return max;
}
//冒泡排序
public static void maoPao(int[] 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]) {
huan(arr,j,j+1);
}
}
}
}
public static void xuanZe(int[] arr) {
for (int i = 0; i < arr.length-1; i++) {
for (int j = i+1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
huan(arr, i, j);
}
}
}
}
private static void huan(int[] arr,int i,int j) {
// TODO Auto-generated method stub
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
4.2 shuzutools 类的调用
package com.qf.test;
import com.qf.tools.ShuZuTools;
public class ToolsTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(ShuZuTools.MATH_PI);
//ShuZuTools.MATH_PI = 9; 常量不能被修改
int[] arr= {10,20,300,80,780,3,2,1};
ShuZuTools.bianLi(arr);
System.out.println(ShuZuTools.getMaxInArr(arr));
ShuZuTools.maoPao(arr);
ShuZuTools.bianLi(arr);
int[] arr2 = {10,29,39,49,20,900};
ShuZuTools.bianLi(arr2);
ShuZuTools.xuanZe(arr2);
ShuZuTools.bianLi(arr2);
}
}
5.代码块
一个 {} 就代表一个块儿
5.1 块
package com.qf.kuai;
public class Demo {
private int num;
public static final int NUM2=10;
public Demo(int num) {
super();
this.num = num;
System.out.println("====构造函数====");
}
{
System.out.println("====构造代码块=每个对象初始化之前都会调用一次=比构造函数更早调用==");
}
static{
System.out.println("====静态代码块===类初始化的时候只会被调用一次======");
}
}
package com.qf.kuai;
public class KuaiTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*{
System.out.println("====代码块====");
}
if (3>1) {
System.out.println("====if语句块====");
}*/
System.out.println(Demo.NUM2);
Demo demo = new Demo(3);
Demo demo2=new Demo(12);
}
}
6.类和对象的加载过程
6.1 Person 类
package com.qf.jiazai;
public class Person {
public static final int NUM=8;
private String name="杨康";
static{}//静态代码块
{}//构造代码块
public Person(String name){this.name=name;}//构造函数
public void setName(String name) {
this.name = name;
}
public static int getNum() {
return Person.NUM;
}
}
6.2 调用person 类
package com.qf.jiazai;
public class JiaZaiTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Person person=new Person("穆念慈");
}
}
7.继承(jichegn。test007)
将一些有共同属性或功能的类抽象出一个类,让子类继承它
只支持单继承,多实现
extends – 继承的关键字
private 私有的不能继承
7.1 person – student
package com.qf.jicheng;
public class Person {
String name;
int age;
public Person(String name, int age) {
super();
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 "Person [name=" + name + ", age=" + age + "]";
}
}
studeng 继承了 person
package com.qf.jicheng;
public class Student extends Person {
String xueHao;
public Student(String name, int age) {
super(name, age);
// TODO Auto-generated constructor stub
}
public Student(String name, int age, String xueHao) {
super(name, age);
this.xueHao = xueHao;
}
public String getXueHao() {
return xueHao;
}
public void setXueHao(String xueHao) {
this.xueHao = xueHao;
}
public void study() {
System.out.println("=====day day up=====");
}
@Override
public String toString() {
return super.toString() + "Student [xueHao=" + xueHao + "]";
}
}
方法的调用
package com.qf.jicheng;
public class Test007 {//extend Object
public static void main(String[] args) {
// TODO Auto-generated method stub
Student student=new Student("李逵", 25,"009");
System.out.println(student);
student.study();
student.setAge(90);
System.out.println(student);
}
}
7.2 fu — 子
fu
package com.qf.jicheng2;
public class Fu {
int num=8;
}
zi
package com.qf.jicheng2;
public class Zi extends Fu{
int num=19;
public void show() {
System.out.println(this.num);
System.out.println(super.num);
}
}
调用
package com.qf.jicheng2;
public class Test001 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Zi zi =new Zi();
zi.show();
}
}
7.3 继承的复写
public > protected 自己和子类可以用 > 默认 > private 私有,不能继承
override – 重写方法
fu
package com.qf.jicheng3;
public class Fu {
//public protected 默认 private
//public > protected>默认
public void show() {
System.out.println("====fu===show===");
}
}
zi
package com.qf.jicheng3;
public class Zi extends Fu{
@Override//опл┤ийие
public void show() {
// TODO Auto-generated method stub
System.out.println("===zi===show====");
}
}
zi 2
package com.qf.jicheng3;
public class Zi2 extends Fu{
@Override
public void show() {
// TODO Auto-generated method stub
super.show();
System.out.println("===保留父类功能==进行方法的扩展===");
}
}
调用
package com.qf.jicheng3;
public class Test001 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Zi zi=new Zi();
zi.show();
System.out.println("+++++++++++++++");
Zi2 zi2=new Zi2();
zi2.show();
}
}
7.4
student – fu
package com.qf.jicheng4;
public class Student {
String name;
int age;
public Student(String name, int age) {
super();
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;
}
public void study() {
System.out.println("====学生爱学习====");
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}
javastudent - zi
package com.qf.jicheng4;
public class JavaStudent extends Student {
public JavaStudent(String name, int age) {
super(name, age);
// TODO Auto-generated constructor stub
}
@Override
public void study() {
// TODO Auto-generated method stub
super.study();
System.out.println("====ѧϰºª·¢=====");
}
}
h5student – zi
package com.qf.jicheng4;
public class H5Student extends Student {
public H5Student(String name, int age) {
super(name, age);
// TODO Auto-generated constructor stub
}
@Override
public void study() {
// TODO Auto-generated method stub
super.study();
System.out.println("===学习前端的开发===");
}
}
调用
package com.qf.jicheng4;
public class Test009 {
public static void main(String[] args) {
// TODO Auto-generated method stub
JavaStudent student=new JavaStudent("诸葛亮", 20);
student.study();
H5Student h5Student=new H5Student("黄忠", 60);
h5Student.study();
}
}
8.final关键字
final – 主要是安全
可以修饰变量 – 修饰变量后就变成常量
可以修饰方法 – 方法将不能被复写
可以修饰一个类 – 这个类将不能被继承
demo - - fu
package com.qf.demofinal;
public class Demo {
public void show1() {
System.out.println("+++++++++++demo---show1===");
}
public final void show2() {//final方法不能被重写
System.out.println("+++++demo---show2====");
}
}
zidemo
package com.qf.demofinal;
public class ZiDemo extends Demo {
@Override
public void show1() {
// TODO Auto-generated method stub
System.out.println("====hehe====");
}
}
package com.qf.demofinal;
public class ChangLiangTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
final int NUM=8;
System.out.println(NUM);
//NUM = 9;
ZiDemo ziDemo=new ZiDemo();
ziDemo.show1();
ziDemo.show2();//show2的内容子类不能变 只能使用
}
}
package com.qf.demofinal;
public final class DingKe {
public void show() {
System.out.println("====dk=show===");
}
public void show2() {
System.out.println("====dk=show2===");
}
}
package com.qf.demofinal;
//public class Zi extends DingKe{//final类不能被继承
public class Zi{
}
9.上帝类 – Object
equals – 相等 – 作用:后面讲去重的时候会用
需要提供原则
hashCode() and equles() – 判断两个对象是否相等,需要给定规则
package com.qf.shangdi;
public class Demo extends Object{
}
package com.qf.shangdi;
public class Test001 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Demo demo = new Demo();
System.out.println(demo);//com.qf.shangdi.Demo@659e0bfd
/*String string = demo.toString();
System.out.println(string);*/
System.out.println(demo.getClass());//class com.qf.shangdi.Demo
System.out.println(demo.getClass().getName());//com.qf.shangdi.Demo
System.out.println(demo.hashCode());//1704856573
System.out.println(Integer.toHexString(demo.hashCode()));//659e0bfd
System.out.println(demo.getClass().getName()+"@"+Integer.toHexString(demo.hashCode()));
System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
//注意:当此方法被重写时,通常有必要重写 hashCode 方法,以维护 hashCode 方法的常规协定,该协定声明相等对象必须具有相等的哈希码。
Person person=new Person("张飞", 20);
Person person2=new Person("张飞", 20);
System.out.println(person.equals(person2));
}
}
package com.qf.shangdi;
public class Person {
private String name;
private int age;
public Person(String name, int age) {
super();
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 "Person [name=" + name + ", age=" + age + "]";
}
//提供一个判断两个对象是否相等的原则 hashcode equals
//注意:当此方法被重写时,通常有必要重写 hashCode 方法,以维护 hashCode 方法的常规协定,该协定声明相等对象必须具有相等的哈希码。
//给的原则是名字相同 年龄相等视为同一人
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
10.构造函数 – 初始化对象的属性
二、抽象类
abstract – 使用这个关键字修饰的类就是抽象类
抽象类是模糊的,不具体的
adstract void fun()
含有抽象方法的类就是抽象类
抽象类不能创建对象,但是可以有子类对象
抽象类的方法是让子类用的,并且限制子类 ,中间的子类可以继续抽象
package com.qf.chouxiang;
public abstract class Qin {
public abstract void fly();//是对子类的限制
}
package com.qf.chouxiang;
public abstract class HomeQin extends Qin {
public abstract void fly();
}
package com.qf.chouxiang;
public class Ya extends HomeQin {
@Override
public void fly() {
// TODO Auto-generated method stub
System.out.println("====水上漂===");
}
}
package com.qf.chouxiang;
public abstract class FlyQin extends Qin {
public abstract void fly();
}
package com.qf.chouxiang;
public class Ying extends FlyQin {
@Override
public void fly() {
// TODO Auto-generated method stub
System.out.println("===гЅЛїГЄПе====");
}
}
package com.qf.chouxiang;
public class Test001 {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* 家养 猫 家禽 鸡
禽类
飞
家禽 鸭 鹅
飞禽 鸿鹄 大雁 雀
*/
Ya ya=new Ya();
ya.fly();
Ying ying=new Ying();
ying.fly();
}
}
三、接口
interface
- 接口是一种能被实现的规则
- 接口的存在都是为了扩展类的功能
- 为了弥补java单继承的缺陷
- 一个java类虽然只能继承一个父类,但是可以通过实现n多接口来扩展自身功能
接口 成员特点:
- 公有常量 – (public static final) int NUM=8 – 括号里面的可以不写
- 公有抽象方法 – (public abstract )void fun()–括号里面的可以不写
类和接口的区别:
- 一个类可以实现一个或多个接口 那这个类就叫这个接口的实现着 也可以叫这个接口的子类
- 一个接口也可以被多个类同时实现 这个时候也可以形成接口体系
接口和接口之间的关系
- 接口和接口之间可以产生继承关系,接口的继承可以多继承
接口的实现过程
- 类1 – 实现了接口里所有的抽象方法 – 可以创建对象
- 类2 – 实现了接口里部分的抽象方法 – 只能把自己变成抽象的(abstract 抽象类),剩下的抽象方法只能让自己的子类实现 – 如果子类实现了剩余的抽象方法,子类就可以创建对象
如果一个类的所有方法都是抽象方法,那这个类就叫接口,如果只有部分抽象方法,就叫抽抽象类
1.接口1
接口 Fly
package com.qf.jiekou;
public interface Fly {
//定义飞的规则 public static abstract
void fly();
}
FlyQin implements Fly
package com.qf.jiekou;
public abstract class FlyQin implements Fly {
}
HongHu extends FlyQin
package com.qf.jiekou;
public class HongHu extends FlyQin {
@Override
public void fly() {
// TODO Auto-generated method stub
System.out.println("====鸿鹄高飞===");
}
}
YanQue extends FlyQin
package com.qf.jiekou;
public class YanQue extends FlyQin {
@Override
public void fly() {
// TODO Auto-generated method stub
System.out.println("====燕雀低飞====");
}
}
AirPlane implements Fly
package com.qf.jiekou;
public abstract class AirPlane implements Fly {
}
ZhiFeiJi extends AirPlane
package com.qf.jiekou;
public class ZhiFeiJi extends AirPlane {
@Override
public void fly() {
// TODO Auto-generated method stub
System.out.println("====扔着飞====");
}
}
FeiJi extends AirPlane
package com.qf.jiekou;
public class FeiJi extends AirPlane {
@Override
public void fly() {
// TODO Auto-generated method stub
System.out.println("====加油飞====");
}
}
Test001
package com.qf.jiekou;
public class Test001 {
public static void main(String[] args) {
// TODO Auto-generated method stub
HongHu hongHu=new HongHu();
hongHu.fly();
YanQue yanQue=new YanQue();
yanQue.fly();
FeiJi feiJi=new FeiJi();
feiJi.fly();
ZhiFeiJi zhiFeiJi=new ZhiFeiJi();
zhiFeiJi.fly();
}
}
2.接口2
class Person
package com.qf.jiekou2;
public class Person {
String name;
int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
interface QiangKill
package com.qf.jiekou2;
public interface QiangKill {
void qiangKill();
}
interface DuKill
package com.qf.jiekou2;
public interface DuKill {
//用毒
void duKill();
}
Killer extends Person implements DaoKIll
package com.qf.jiekou2;
public Killer extends Person implements DaoKIll {
void daoKill();
}
Killer extends Person implements DaoKIll
package com.qf.jiekou2;
public class Killer extends Person implements DaoKIll, DuKill, QiangKill {
public Killer(String name, int age) {
super(name, age);
// TODO Auto-generated constructor stub
}
@Override
public void qiangKill() {
// TODO Auto-generated method stub
System.out.println("====һǹ±Ѓü=====");
}
@Override
public void duKill() {
// TODO Auto-generated method stub
System.out.println("====º¬Ц°벽===");
}
@Override
public void daoKill() {
// TODO Auto-generated method stub
System.out.println("====һµ¶±Ѓü======");
}
}
Test001
package com.qf.jiekou2;
public class Test001 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Killer killer=new Killer("¾£ינ", 30);
System.out.println(killer);
killer.daoKill();
killer.duKill();
killer.qiangKill();
}
}
3.抽象类和接口的区别
先说抽象类—再说接口 —再说区别
1.抽象类可以有非抽象方法,接口只能有抽象方法
2.抽象类可以有任何类型的变量,接口只能有常量
3.抽象类只能单继承,接口可以多实现,接口之间可以多继承
4.当重写抽象类方法时,不一定是public ,接口的必须是public
5.抽象类的方法必须写adstract修饰符,接口的可以省略
四、多态
一个事物的多种体现形态,没有继承就没有多态
多态的本质:
- 父类引用指向了子类对象
- 父类的引用也可以接收子类对象
1.多态实例
Animal
package com.qf.duotai;
public abstract class Animal {
public abstract void eat();
}
Mao 继承 Animal
package com.qf.duotai;
public class Mao extends Animal {
@Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("====我是一只猫====");
System.out.println("===猫吃鱼====");
}
}
Sheep 继承 Animal
package com.qf.duotai;
public class Sheep extends Animal {
@Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("====我是一只羊====");
System.out.println("====羊吃草===");
}
}
Wolf 继承 Animal
package com.qf.duotai;
public class Wolf extends Animal {
@Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("====我是一匹狼====");
System.out.println("====狼吃羊===");
}
}
test
package com.qf.duotai;
public class Test001 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Mao mao=new Mao();
mao.eat();
Mao mao2=new Mao();
mao2.eat();
System.out.println("+++++++++++++++++++++++");
dongWuEat(mao);
dongWuEat(mao2);
dongWuEat(new Wolf());
dongWuEat(new Sheep());
System.out.println("+++++++++++++++++++++++++++++++");
System.out.println(getAnimal(1));
System.out.println(getAnimal(2));
System.out.println(getAnimal(3));
getAnimal(1).eat();
getAnimal(2).eat();
getAnimal(3).eat();
System.out.println("+++++++++++++++++++=");
dongWuEat(getAnimal(1));
dongWuEat(getAnimal(2));
dongWuEat(getAnimal(3));
}
//动物吃
public static void dongWuEat(Animal animal) {//animal--eat Animal animal=new 子类对象
animal.eat();
}
//根据参数来获取不同的动物对象
//1---mao 2 wolf 3 sheep
public static Animal getAnimal(int num) {
Animal animal=null;
switch (num) {
case 1:
animal = new Mao();
break;
case 2:
animal = new Wolf();
break;
case 3:
animal=new Sheep();
break;
default:
System.out.println("----参数有误===");
break;
}
return animal;
}
}
2.多态的转型(duotai2)
2.1 dongwu – zilei (mao,wolf)
DongWu 类
package com.qf.duotai2;
public abstract class DongWu {
public abstract void eat();
}
Mao 继承 DongWu
package com.qf.duotai2;
public class Mao extends DongWu {
@Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("====猫吃鱼=====");
}
//特有方法
public void catchMouse() {
System.out.println("=====抓老鼠=====");
}
}
wolf 继承 DongWu
package com.qf.duotai2;
public class Wolf extends DongWu {
@Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("===狼吃羊=====");
}
}
test
package com.qf.duotai2;
public class Test001 {
public static void main(String[] args) {
// TODO Auto-generated method stub
DongWu dongWu=new Mao();
Mao mao1 =new Mao();
dongWu.eat();
dongWu = new Wolf();
//Mao mao = (Mao)dongWu;//把这个动物强制转型成猫//类型转换异常 java.lang.ClassCastException: com.qf.duotai2.Wolf cannot be cast to com.qf.duotai2.Mao
if (dongWu instanceof Mao) {
System.out.println("===是猫===");
}else {
System.out.println("===不是猫===");
}
dongWu = new Mao();
//子类对象在想调用自己特有方法的时候 必须先把自己转成自己的类型 才可以调用
if (dongWu instanceof Mao) {
Mao mao=(Mao) dongWu;//把动物强转成猫
mao.catchMouse();
}
}
}
3.多态中的成员特点(多态三)
package com.qf.duotai3;
public class Fu1 {
int num=19;
public void show() {
System.out.println("===fu===show===");
}
public static void fun1() {
System.out.println("====fu===static===");
}
}
package com.qf.duotai3;
public class Zi1 extends Fu1 {
int num=7;
@Override
public void show() {
// TODO Auto-generated method stub
System.out.println("===zi---show===");
}
public static void fun1() {
System.out.println("====zi===static===");
}
}
package com.qf.duotai3;
public class Test001 {
public static void main(String[] args) {
Fu1 zi=new Zi1();
//变量和静态方法看左面 一般看右面
System.out.println(zi.num);
zi.fun1();
zi.show();
}
}
4.抽象类多态的练习 多态4
package com.qf.duotai4;
public abstract class Employee {
//员工都得工作
public abstract void work();
}
package com.qf.duotai4;
public class RuanJian extends Employee {
@Override
public void work() {
// TODO Auto-generated method stub
System.out.println("====开发工作====");
}
}
package com.qf.duotai4;
public class CaiWu extends Employee {
@Override
public void work() {
// TODO Auto-generated method stub
System.out.println("====算账====");
}
}
package com.qf.duotai4;
public class Tester extends Employee {
@Override
public void work() {
// TODO Auto-generated method stub
System.out.println("====ฒโสินคื๗====");
}
}
package com.qf.duotai4;
public class Test001 {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* 需求:
现在有不同类型的员工 软件工程师 测试工程师
使用一个方法来调用员工工作,不同类型员工工作内容不同
*/
letWork(new RuanJian());
letWork(new Tester());
letWork(new CaiWu());
}
//写一个方法 让员工工作
public static void letWork(Employee employee) {
employee.work();
}
}
5.接口的多态练习 多态5
package com.qf.duotai5;
public interface Warning {
//报警功能
void baoJing();
}
package com.qf.duotai5;
public abstract class Door implements Warning {
}
package com.qf.duotai5;
public class WoodDoor extends Door {
@Override
public void baoJing() {
// TODO Auto-generated method stub
System.out.println("=====门铃======");
}
}
package com.qf.duotai5;
public class ElecDoor extends Door {
@Override
public void baoJing() {
// TODO Auto-generated method stub
System.out.println("======音乐报警====");
}
}
package com.qf.duotai5;
public abstract class WaringCar implements Warning {
}
package com.qf.duotai5;
public class PoliceCar extends WaringCar {
@Override
public void baoJing() {
// TODO Auto-generated method stub
System.out.println("======警笛======");
}
}
package com.qf.duotai5;
public class EmerCar extends WaringCar {
@Override
public void baoJing() {
// TODO Auto-generated method stub
System.out.println("=====救命警报=======");
}
}
package com.qf.duotai5;
public class Test001 {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* 当一个接口被多个类实现的时候,在使用这些实现类对象的时候,
可以用接口的引用来充当功能的参数,可以提高代码的扩展性
警报例子 门 警车 救护车
*/
baoJingQi(new WoodDoor());
baoJingQi(new ElecDoor());
baoJingQi(new PoliceCar());
baoJingQi(new EmerCar());
Warning warning=new PoliceCar();
}
//写一个可以报警的方法
public static void baoJingQi(Warning warning) {//Warning warning---接口的引用 接口的引用也可以作为一种类型来接收子类对象
warning.baoJing();
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-iwNSnmjU-1679826670005)(C:\Users\11700\AppData\Roaming\Typora\typora-user-images\image-20220526145031922.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rgef7a94-1679826670007)(C:\Users\11700\AppData\Roaming\Typora\typora-user-images\image-20220526145106551.png)]
五、异常处理
类 Throwable :所有错误和异常的super类
error:
- OutofMemoryError (oom)内存溢出错误
- StackOverflowError-- 栈溢出
Exception 异常:
- ArithmeticException-- 数学运算异常
- ClassCastException – 类型转换异常
- ArrayIndexOutOfBoundsException – 数组下标越界异常
- NullPointerException-- 空指针异常
异常:代码出现了不可控制的不正常的现象
为什么要处理异常:异常一旦出现 代码的运行会受到影响
异常处理:
捕获
try{被监测的代码 可能有异常
}catch(Execption){//类型
检查到了 在这里处理
}finally{不管出不出现都得执行(必须要做的事情)
}
抛
1 – > 2 – 发现异常 抛–> 3 – > 4 发现了你不是自己的
1 – > 2 <-- 处理异常 — 3 <-抛- 4
package com.qf.yichang;
public class Animal {
}
package com.qf.yichang;
public class Cat extends Animal {
}
package com.qf.yichang;
public class Dog extends Animal{
}
package com.qf.yichang;
public class YiChang001 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//int a=1/0;// java.lang.ArithmeticException: / by zero//数学运算异常
Animal animal=new Cat();
//Dog dog=(Dog) animal;// java.lang.ClassCastException: com.qf.yichang.Cat cannot be cast to com.qf.yichang.Dog、、类型转换异常
System.out.println("====关键代码=====");
int[] arr={1,2,3};
//arr[10] = 10;// java.lang.ArrayIndexOutOfBoundsException: 10//数组下标越界异常
//arr = null;
//System.out.println(arr.length);//java.lang.NullPointerException---空指针异常
}
}
1.捕获
package com.qf.yichang;
public class YiChang002 {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
System.out.println("=]====begin====");
int a = 10;
int[] arr ={1,2,3};
//arr[10] = 9;
System.out.println("'''''''''''");
a=0;
int x = 10/a;
System.out.println("===功能001====");
System.out.println("=====over===");
} catch (ArithmeticException e) {
// TODO Auto-generated catch block
System.out.println("=======001=======");
e.printStackTrace();
}catch (ArrayIndexOutOfBoundsException e) {
// TODO: handle exception
System.out.println("=======002=======");
e.printStackTrace();
}finally {
System.out.println("===保护代码====");
}
try {
} catch (Exception e) {
// TODO: handle exception
}finally {
}
}
}
2.抛(yichang3、tools)
package com.qf.yichang;
public class Tools {
//写一个方法进行除法运算
public static double chu(int a,int b) throws Exception {//throws Exception这个方法在某种情况下会抛异常
if (b==0) {
throw new Exception("=====不要传0进来 接受不了===");
}
double shang = a/b;
return shang;
}
}
package com.qf.yichang;
public class Yichang3 {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
//在一个用户的E盘创建一个文件夹
try {
} catch (Exception e) {
// TODO: handle exception
}
int a = 9;
int b=0;
double result = 0;
if (b!=0) {
result = letChu(a, b);
}
/*try {
result = letChu(a, b);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
System.out.println(result);
System.out.println("=======关键功能======");
}
//
public static double letChu(int a,int b) throws Exception {
double jieguo = Tools.chu(a, b);
return jieguo;
}
}
六、封装类
1.基本数据类型的封装类(Test001)
bool – >Boolean、byte – >Byte、short --> Short、int --> Integre、long --> Long、float --> Float、double --> Double 、char – >Character
- parseInt,parseXXX,…将字符串转成xxx型
package com.qf.fengzhuanglei;
public class Test001 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a=10;
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
System.out.println(Byte.MAX_VALUE);
System.out.println(Byte.MIN_VALUE);
System.out.println(Short.MAX_VALUE);
System.out.println(Short.MIN_VALUE);
System.out.println(Byte.SIZE);
System.out.println(Integer.SIZE);
System.out.println("======自动装箱 和自动拆箱====");
Integer integer=new Integer(10);
System.out.println(integer);
Integer integer2=10;//自动装箱就是将一个基本类型的值装箱成对象
System.out.println(integer2);
int x = 8+integer;//自动拆箱 意思是可以将一个封装类的对象的值直接拆出来当基本类型使用
System.out.println(x);
System.out.println("+++++++++得到一个数字的不同进制+++++++++++++++++++++++++");
int y=100;
System.out.println(Integer.toBinaryString(y));
System.out.println(Integer.toOctalString(y));
System.out.println(Integer.toHexString(y));
System.out.println("==========将一个字符串形式的进制转成int数字====");
System.out.println(Integer.parseInt("10"));
System.out.println(Integer.parseInt("1111", 2));
System.out.println(Integer.parseInt("11", 8));
System.out.println(Integer.parseInt("11", 16));
System.out.println(Double.parseDouble("9.9"));
System.out.println(Boolean.parseBoolean("true"));
System.out.println(Boolean.parseBoolean("1"));
System.out.println("+++++++++++常用数字范围地址一样 Byte范围 -128-127 ++++++++++++++++++++++++");
Integer in1 = 200;
Integer in2 = 200;
System.out.println(in1 == in2);
}
}
2.输入类 scanner
package com.qf.shuru;
import java.util.Scanner;
public class DemoScanner {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("===打印输出====");
System.out.println(System.in);
System.out.println("=====使用scanner来控制用户的输入====");
Scanner scanner=new Scanner(System.in);//System.in---控制台输入
System.out.println("====请输入用户名:===");
String name = scanner.next();//这是一个阻塞方法 会等着用户输入
System.out.println(name);
System.out.println("+++++++亲输入年龄===");
int age = scanner.nextInt();
System.out.println(age);
}
}
3.system 类(DemoSystem)
System.currentTimeMillis()
— 系统时间
Properties properties = System.getProperties(key);
– 系统属性的获取和设置
Proper
设置环境变量:
package com.qf.changyonglei2;
import java.util.Properties;
public class DemoSystem {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(System.currentTimeMillis());
jiSuanTime();
Properties properties = System.getProperties();
System.out.println(properties);
System.out.println("+++++++++++++++++");
String property = System.getProperty("java.home");
System.out.println(property);
System.setProperty("kk", "Killer");
}
public static void jiSuanTime() {
long start = System.currentTimeMillis();
fun1();
long end = System.currentTimeMillis();
System.out.println(end-start);
}
public static void fun1() {
int sum=0;
for (int i = 0; i < 100000; i++) {
sum += i;
}
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wmbXscRa-1679826670007)(C:\Users\11700\AppData\Roaming\Typora\typora-user-images\image-20220527093922140.png)]
4.运行时 Runtime
package com.qf.changyonglei2;
import java.io.IOException;
public class DemoRuntime {
public static void main(String[] args) {
// TODO Auto-generated method stub
Runtime runtime = Runtime.getRuntime();//得到当前的运行时类
Process exec=null;
try {
exec = runtime.exec("c:/winmine.exe");//一运行就能得到一个进程
System.out.println("=====试玩开始=====");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
exec.destroy();
System.out.println("====试玩结束====");
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-r68eT7W4-1679826670008)(C:\Users\11700\AppData\Roaming\Typora\typora-user-images\image-20220527095158298.png)]
5.日期 Date
package com.qf.changyonglei2;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DemoDate {
public static void main(String[] args) {
// TODO Auto-generated method stub
Date date=new Date(System.currentTimeMillis());
System.out.println(date);
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
String format = dateFormat.format(date);
System.out.println(format);
SimpleDateFormat dateFormat2=new SimpleDateFormat("yyyy年MM月dd日");
String format2 = dateFormat2.format(date);
System.out.println(format2);
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7sEfnNZk-1679826670008)(C:\Users\11700\AppData\Roaming\Typora\typora-user-images\image-20220527095955859.png)]
6.日历 Calendar
package com.qf.changyonglei2;
import java.util.Calendar;
public class DemoCalendar {
public static void main(String[] args) {
// TODO Auto-generated method stub
Calendar instance = Calendar.getInstance();
System.out.println(instance);
System.out.println(instance.get(Calendar.YEAR));
//System.out.println(Calendar.YEAR);
System.out.println(instance.get(Calendar.DAY_OF_MONTH));
System.out.println(instance.get(Calendar.MONTH));
System.out.println(instance.get(Calendar.DAY_OF_WEEK));
String[] weeks={"星期六","星期天","星期一","星期二","星期三","星期四","星期五"};
String[] yue={"一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"};
System.out.println(weeks[instance.get(Calendar.DAY_OF_WEEK)]);
System.out.println(yue[instance.get(Calendar.MONTH)]);
System.out.println("======================");
instance.add(Calendar.YEAR, -10);
System.out.println(instance.get(Calendar.YEAR));
}
}
7.数学类 Math
package com.qf.changyonglei2;
public class DemoMath {
public static void main(String[] args) {
// TODO Math类
System.out.println(Math.PI);
System.out.println(Math.E);
System.out.println(Math.abs(-9));
System.out.println(Math.abs(9));
System.out.println(Math.cbrt(8));//立方根
System.out.println(Math.floor(9.99));
System.out.println(Math.ceil(9.001));
System.out.println(Math.log(Math.E));
System.out.println(Math.log10(100));
System.out.println(Math.max(10, 8));
System.out.println(Math.max(10, Math.max(2, 3)));
System.out.println(Math.min(2, 10));
System.out.println(Math.pow(2, 3));
System.out.println("+++++++++++++++++++++++++");
for (int i = 0; i < 10; i++) {
System.out.println((int)(Math.random()*100));
}
System.out.println("++++++++++++++++++");
System.out.println(Math.round(4.9));
System.out.println(Math.round(4.56));
System.out.println("++++++++++++++++");
System.out.println(Math.sqrt(9));
}
}
七、字符串(重要)
1.字符串的创建和方法
fun4()重要
package com.qf.zifuchuan;
import java.util.Scanner;
import com.qf.home.home3.GaiBang;
public class DemoString {
public static void main(String[] args) {
// TODO Auto-generated method stub
fun4();
}
public static void fun4() {
//首先接收键盘输入
Scanner scanner=new Scanner(System.in);
//这时候可以使用next一次接受输入的数字 接收的内容是字符串
System.out.println("===请输入====");
String next = scanner.next();
System.out.println(next);
//通过切割方法得到其中的数字数组
String[] nums = next.split(",");
//将字符串数组转换成数字数字
int[] numInt = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
numInt[i] = Integer.parseInt(nums[i]);
}
System.out.println("=====转换成功=做运算了===");
int sum=0;
for (int i : numInt) {
sum+=i;
}
System.out.println(sum);
}
private static void fun3() {
// TODO Auto-generated method stub
/*
* split
replace
subString
1,2,3,4,5
90
*/
Scanner scanner=new Scanner(System.in);
System.out.println("===请输入五个数字====");
String next = scanner.next();
System.out.println(next);
String[] nums = next.split(",");
System.out.println(nums);
int[] numsInt = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
numsInt[i] = Integer.parseInt(nums[i]);//将字符串转换成int
//parseDouble parseBoolean parseByte
}
System.out.println(numsInt);
System.out.println("+++++++++++++++++++++++");
int max=numsInt[0];
for (int i : numsInt) {
if (i>max) {
max = i;
}
}
System.out.println(max);
}
private static void fun2() {
// TODO Auto-generated method stub
/*
* 原则 不管对字符串做什么操作,源字符串不变,变化后生成一个新字符串
大小写
toUpperCase()
toLowerCase()
字符数组
字符数组转字符串使用构造方法
字符串转字符数组使用toCharArray();
字节数组
byte[] b=s.getBytes();
new String(byte[]);
基本数据类型转string
String.valueOf(Object object);
去除空格 比较
trim()
compareTo---从首位开始比,如果一样才往后比
*/
String string="Killer IS qq";
System.out.println(string);
System.out.println(string.toLowerCase());
System.out.println(string.toUpperCase());
System.out.println("+++++++++++++++++++++++++");
char[] charArray = string.toCharArray();
for (char c : charArray) {
System.out.print(c+",");
}
System.out.println();
char[] cs2 = new char[6];
for (int i = 0; i < 6; i++) {
cs2[i] = charArray[i];
}
for (char c : cs2) {
System.out.println(c+",");
}
System.out.println(new String(cs2));
System.out.println("+++++++++++++++++++++");
String ss = ""+new Object();
System.out.println(ss);
String ss2 = ""+new GaiBang("黄蓉", 20);
System.out.println(ss2);
}
public static void fun0() {
String string="hello";//字符串对象是常量 一经定义无法更改
String string2 = new String("like");
char[] cs = {'a','1','k'};
String string3 = new String(cs);
System.out.println(string3);
byte[] bytes = "killer".getBytes();
String string4 = new String(bytes);
System.out.println(string4);
}
public static void fun1() {
/*
* 1:获取:
indexOf
lastIndexOf
charAt
length
2: 判断
---判断字符串是否为空 isEmpty()
contains
---判断一个字串里面是否含有某一个子串
---判断文件名 判断文件名是否含有什么内容
判断文件名是否以什么开始 判断文件名类型
*/
String string="killer and killer";
System.out.println(string.indexOf("er"));//找子串第一次出现的位置
System.out.println(string.indexOf("er", 5));//从5开始找
System.out.println(string.lastIndexOf("er"));
System.out.println(string.lastIndexOf("er", 14));
System.out.println(string.charAt(0));
System.out.println(string.length());
System.out.println("+++++++++++++++判断+++++++++++++++++++++++++");
System.out.println(string.isEmpty());
String[] files = {"qq.java","killer.java","ss.png","qqqqq.png","zizi.png"};
for (String filename : files) {
if (filename.contains("qq")) {
System.out.println(filename);
}
}
System.out.println("+++++++++++++startwith++++++++++++++++++++");
for (String filename : files) {
if (filename.startsWith("qq")) {
System.out.println(filename);
}
}
System.out.println("+++++++++++++endswith++++++++++++++++++++");
for (String filename : files) {
if (filename.endsWith(".java")) {
System.out.println(filename);
}
}
}
}
2.字符串的容器类 stringBuilder 增删改查
stringBuffer、stringBuilder 两者的区别:
stringBuilder
- 线程不同步,执行速度块,线程不安全
stringBuffer
- 线程同步,执行速度比stringBuilder慢,但线程安全
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dUWqxn0P-1679826670009)(C:\Users\11700\AppData\Roaming\Typora\typora-user-images\image-20220527140405245.png)]
package com.qf.zifuchuan;
public class DemoStringBuilder {
public static void main(String[] args) {
// TODO Auto-generated method stub
time();
}
public static void fun4() {
StringBuilder stringBuilder=new StringBuilder();
for (int i = 0; i < 100000; i++) {
stringBuilder.append("hello");
}
}
public static void fun3() {
StringBuffer stringBuffer=new StringBuffer();
for (int i = 0; i < 100000; i++) {
stringBuffer.append("hello");
}
}
public static void fun2() {
String string="";
for (int i = 0; i < 30000; i++) {
string +="hello";
}
}
public static void time() {
long start = System.currentTimeMillis();
fun4();
long end = System.currentTimeMillis();
System.out.println(end-start);
}
public static void fun1() {
//StringBuilder---一个字符串的容器
//增删改查
StringBuilder stringBuilder=new StringBuilder();
System.out.println(stringBuilder);
StringBuilder stringBuilder2=new StringBuilder("hello:");
System.out.println(stringBuilder2);
System.out.println("=====增加=append==");
stringBuilder2.append('汗');
//"a" 'a' 8
System.out.println(stringBuilder2);
stringBuilder2.append("killer");
System.out.println(stringBuilder2);
System.out.println(stringBuilder2.charAt(0));
System.out.println("=====删除====delete=");
System.out.println(stringBuilder2.deleteCharAt(6));
System.out.println(stringBuilder2.delete(2, 5));//前包后不包
System.out.println("====插入内容===insert==");
stringBuilder2.insert(3, "today");
System.out.println(stringBuilder2);
System.out.println("++++++++++==替换=======");
stringBuilder2.replace(3,8, "tomorrow");
System.out.println(stringBuilder2);
System.out.println("=====反转====");
stringBuilder2.reverse();
System.out.println(stringBuilder2);
System.out.println("=====修改===");
stringBuilder2.setCharAt(0, 'Q');
System.out.println(stringBuilder2);
stringBuilder2.reverse();
System.out.println(stringBuilder2);
String zichuan1 = stringBuilder2.substring(stringBuilder2.indexOf("kill"));
System.out.println(zichuan1);
String zichuan2 = stringBuilder2.substring(3, 7);
System.out.println(zichuan2);
}
}
测试执行时间
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JNmPGr7i-1679826670010)(C:\Users\11700\AppData\Roaming\Typora\typora-user-images\image-20220527142126829.png)]
八、集合 Collection
1.集合的分类
Collection是一个接口,有两个子类 List 和 Set
- List 有序且可以重复 (有序是指跟存储顺序一致)
- ArrayList 数组结构
- LinkedList 链表结构
- Set 无序不能重复
- HashSet 哈希表结构
- TreeSet 二叉树结构
接口Collection 指泛型 — 泛指类型 ,在指明之前任何一个类的名字都可以,指明之后就确定了,只能放这个类
1.1 Collection 方法
增删改查和遍历
List(接口) 方法(在collection里面):
- ArrayList 的方法 arrayList 集合
- arrayList.add(values) /arrayList.add(index,values) – 增加元素
- arrayList.remove(index) – 删除元素
- arrayList.set(index,values) – 修改元素
- arrayList.get(index) – 得到元素
- LinkedList 的方法
- linkedList.add(values) /arrayList.add(index,values) – 增加元素
- linkedList.remove(index) – 删除元素
- linkedList.set(index,values) – 修改元素
- linkedList.get(index) – 得到元素
package com.qf.jihe;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
public class DemoCollection {
public static void main(String[] args) {
// TODO Auto-generated method stub
fun4();
}
private static void fun4() {
// TODO Auto-generated method stub
LinkedList<String> linkedList=new LinkedList<>();
linkedList.addFirst("刘备");
linkedList.addFirst("关羽");
linkedList.addFirst("赵云");
linkedList.addFirst("诸葛");
linkedList.addFirst("黄忠");
linkedList.addFirst("张飞");
System.out.println(linkedList);
Iterator<String> iterator = linkedList.iterator();
while (iterator.hasNext()) {
String string = (String) iterator.next();
System.out.println(string);
}
}
//linkedlist的方法
public static void fun3() {
LinkedList<String> linkedList=new LinkedList<>();
linkedList.add("张飞");
System.out.println(linkedList);
linkedList.addFirst("关羽");
System.out.println(linkedList);
linkedList.offerFirst("刘备");
System.out.println(linkedList);
String removeFirst = linkedList.removeFirst();
System.out.println(removeFirst);
System.out.println(linkedList);
String pollFirst = linkedList.pollFirst();
System.out.println(pollFirst);
System.out.println(linkedList);
linkedList.addLast("曹操");
System.out.println(linkedList);
linkedList.offerLast("孙权");
System.out.println(linkedList);
linkedList.offerLast("吕布");
System.out.println(linkedList);
System.out.println("++++++++++++++++++++==");
Iterator<String> iterator = linkedList.iterator();
while (iterator.hasNext()) {
String string = (String) iterator.next();
//linkedList.remove("曹操");// java.util.ConcurrentModificationException
System.out.println(string);
if (string.equals("曹操")) {
iterator.remove();
}
}
System.out.println("++++++++++++++++++++=");
String removeLast = linkedList.removeLast();
System.out.println(removeLast);
System.out.println(linkedList);
String pollLast = linkedList.pollLast();
System.out.println(pollLast);
System.out.println(linkedList);
}
//ArrayList的方法
public static void fun2() {
ArrayList<String> list=new ArrayList<>();
list.add("qq");
list.add("ww");
System.out.println(list);
list.add(1, "killer");//在下标为1的位置上增加killer
System.out.println(list);
list.add(1,"today");
System.out.println(list);
System.out.println("+++++根据下标获取=====");
System.out.println(list.get(2));
list.remove(2);//删除下标为2的元素
System.out.println(list);
list.remove("qq");
System.out.println(list);
list.set(0, "uu");//set -- 修改元素
System.out.println(list);
}
//Collection的方法
public static void fun1() {
Collection<Integer> collection=new ArrayList<>();
System.out.println("=====增加===========");
collection.add(10);
collection.add(12);
collection.add(90);
collection.add(8);
System.out.println(collection);
Collection<Integer> collection2=new ArrayList<>();
collection2.add(110);
collection2.add(180);
System.out.println(collection2);
collection.addAll(collection2);
System.out.println(collection);
System.out.println(collection2);
System.out.println("+++++++++++判断有没有+++++++++++++++=");
System.out.println(collection.containsAll(collection2));
System.out.println(collection.contains(10));
System.out.println("++++++++++++++删除++++++++++++++++");
collection.removeAll(collection2);
System.out.println(collection);
collection.remove(90);
System.out.println(collection);
System.out.println(collection.isEmpty());
//collection.clear();
System.out.println(collection);
System.out.println(collection.isEmpty());
System.out.println("+++++++++求交集++++++++++++++++++++++");
Collection<Integer> collection3=new ArrayList<>();
collection3.add(10);
collection3.add(99);
collection3.add(8);
System.out.println(collection);
System.out.println(collection3);
collection.retainAll(collection3);//交集
System.out.println(collection);
System.out.println(collection.size());
System.out.println("++++++++++++++++集合的遍历+++++++++++++++++++");
collection.add(999);
collection.add(190);
collection.add(77);
System.out.println(collection);
for (Integer integer : collection) {
System.out.println(integer);
}
System.out.println("++++++++++集合的迭代器的遍历方式++++++++++");
Iterator<Integer> iterator = collection.iterator();
while (iterator.hasNext()) {
Integer integer = (Integer) iterator.next();
System.out.println(integer);
}
}
}
1.3 Person
package com.qf.jihe;
public class Person {
private String name;
private int age;
public Person(String name, int age) {
super();
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 "Person [name=" + name + ", age=" + age + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
testPeson
package com.qf.jihe;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class TestPerson {
public static void main(String[] args) {
// TODO Auto-generated method stub
//fun1();
ArrayList<Person> persons=new ArrayList<>();
persons.add(new Person("曹操", 26));
System.out.println(persons);
persons.add(new Person("关羽", 20));
persons.add(new Person("刘备", 30));
persons.add(new Person("张飞", 18));
persons.add(new Person("关羽", 20));
persons.add(new Person("刘备", 30));
persons.add(new Person("张飞", 18));
System.out.println(persons);
Iterator<Person> iterator = persons.iterator();
System.out.println("+++++++++++++++++++++++++++++++++++++");
while (iterator.hasNext()) {
Person person = (Person) iterator.next();
System.out.println(person);
}
System.out.println("++++++++去重++++++++++++++++++");
ArrayList<Person> quChong = quChong(persons);
Iterator<Person> iterator2 = quChong.iterator();
while (iterator2.hasNext()) {
Person person = (Person) iterator2.next();
System.out.println(person);
}
}
//写一个方法 根据一个数字来获取一个人
public static Person name(int num) {
return null;
}
//去重
//写一个方法 对一个含有重复元素的list进行去重
public static ArrayList<Person> quChong(ArrayList<Person> persons) {
//先定义一个空的list
ArrayList<Person> persons2 = new ArrayList<>();
for (Person person : persons) {
if (!persons2.contains(person)) {
persons2.add(person);
}
}
return persons2;
}
private static void fun1() {
// TODO Auto-generated method stub
ArrayList<Person> persons=new ArrayList<>();
persons.add(new Person("曹操", 26));
System.out.println(persons);
persons.add(new Person("关羽", 20));
persons.add(new Person("刘备", 30));
persons.add(new Person("张飞", 18));
System.out.println(persons);
System.out.println("++++++++++++++++++++++++++++++++++++");
Iterator<Person> iterator = persons.iterator();
while (iterator.hasNext()) {
Person person = (Person) iterator.next();
System.out.println(person);
}
}
}
九、Set 集合
无序且不可重复,无序指的是与存储顺序不一定一致
1.HashSet
HashSet (哈希表结构)
- 只关注唯一,不关注顺序
TreeSet(二叉树结构)
- 左边一定比右边小,左边比自己小,右边比自己大
- 既能保证唯一还能保证顺序
package com.qf.set1;
import java.util.HashSet;
import java.util.TreeSet;
public class DemoHashSet {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*set1();
System.out.println("=========");
set2();*/
/*stringInSet1();
System.out.println("++++++++++++++++");
stringInTreeset();*/
//duixiangInHashSet();
duixiangInTreeset();
}
public static void duixiangInTreeset() {
TreeSet<Person> persons=new TreeSet<>();
persons.add(new Person("关羽", 20));//Exception in thread "main" java.lang.ClassCastException: com.qf.set1.Person cannot be cast to java.lang.Comparable----因为person没有比较性,没办法比较大小所以无法存储到persons中
persons.add(new Person("张飞", 18));
persons.add(new Person("刘备", 22));
persons.add(new Person("曹操", 20));
System.out.println(persons);
}
public static void duixiangInHashSet() {
HashSet<Person> persons =new HashSet<>();//当一个类对象存储到hashset中 如果需要去重 必须实现hashcod equals方法
persons.add(new Person("关羽", 20));
persons.add(new Person("关羽", 20));
persons.add(new Person("关羽", 20));
persons.add(new Person("关羽", 20));
persons.add(new Person("关羽", 2));
persons.add(new Person("张飞", 2));
System.out.println(persons);
}
public static void stringInTreeset() {
TreeSet<String> set=new TreeSet<>();
set.add("aa");
set.add("xx");
set.add("aa");
set.add("uu");
set.add("killer");
set.add("kill");
set.add("ak");
System.out.println(set);
}
public static void stringInSet1() {
HashSet<String> set=new HashSet<>();
set.add("aa");
set.add("xx");
set.add("aa");
set.add("uu");
set.add("killer");
System.out.println(set);
}
public static void set1() {
HashSet<Integer> set=new HashSet<>();
set.add(10);
set.add(1);
set.add(10);
set.add(8);
set.add(100);
System.out.println(set);
}
public static void set2() {
TreeSet<Integer> set=new TreeSet<>();
set.add(8);
set.add(100);
set.add(10);
set.add(1);
set.add(10);
System.out.println(set);
}
}
package com.qf.set1;
public class Person implements Comparable<Person>{
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
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 "Person [name=" + name + ", age=" + age + "]";
}
@Override
public int compareTo(Person o) {
// TODO this跟参数这两个对象比较大小 return 正数 表示大 负数 表示小 0 表示 相等
//提供的是一种比较规则 根据年龄比较大小
int ageVs = this.age - o.age;
//当首要条件相等 就要比较次要条件
if (ageVs == 0) {
return this.name.compareTo(o.name);
}
return ageVs;
}
}
1.1 在class中没有比较规则时,在class外添加规则
package com.qf.set1;
public class XiGua {
private String color;
private double weight;
public XiGua(String color, double weight) {
super();
this.color = color;
this.weight = weight;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
@Override
public String toString() {
return "XiGua [color=" + color + ", weight=" + weight + "]";
}
}
package com.qf.set1;
import java.util.Comparator;
public class ComXiGua implements Comparator<XiGua> {
@Override
public int compare(XiGua xg1, XiGua xg2) {
// TODO 主要条件是重量 次要条件是颜色
//先比较重量 重量相等比较颜色
Double weight1 = xg1.getWeight();
Double weight2 = xg2.getWeight();
int weightVs = weight1.compareTo(weight2);
if (weightVs == 0) {//主要条件相等 比较次要条件
return xg1.getColor().compareTo(xg2.getColor());
}
return weightVs;
}
}
public class DemoHashSet {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*set1();
System.out.println("=========");
set2();*/
/*stringInSet1();
System.out.println("++++++++++++++++");
stringInTreeset();*/
//duixiangInHashSet();
//duixiangInTreeset();
//appleInTreeSet();
//bijiaoqiDemo1();
//bijiaoqiDemo2();
//bijiaoqiDemo3();
}
public static void bijiaoqiDemo1() {
//TreeSet<XiGua> xiGuas=new TreeSet<>(new ComXiGua());//在Treeset的构造函数中传一个比较器对象
TreeSet<XiGua> xiGuas=new TreeSet<>(new Com2XiGua());
xiGuas.add(new XiGua("绿的", 10));
xiGuas.add(new XiGua("黄的", 7));
xiGuas.add(new XiGua("黄的", 6));
xiGuas.add(new XiGua("绿的", 6));
xiGuas.add(new XiGua("黄的", 4));
xiGuas.add(new XiGua("绿的", 5));
for (XiGua xiGua : xiGuas) {
System.out.println(xiGua);
}
}
}
1.2 比较器取反
沿用上面的 xigua class
结果看上面1.1中的最后一个
package com.qf.set1;
import java.util.Comparator;
public class Com2XiGua implements Comparator<XiGua> {
@Override
public int compare(XiGua xg1, XiGua xg2) {
// TODO Auto-generated method stub
Double weight1 = xg1.getWeight();
Double weight2 = xg2.getWeight();
int weightVs = weight2.compareTo(weight1);
if (weightVs == 0) {
return xg2.getColor().compareTo(xg1.getColor());
}
return weightVs;
}
}
1.3 set test
package com.qf.set2;
import java.util.TreeSet;
public class BiJiaoQiTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
bjqDemo3();
}
public static void bjqDemo3() {
TreeSet<String> set=new TreeSet<>(new ComString());
set.add("hehe");
set.add("hello");
set.add("aha");
set.add("killerkiller");
set.add("xx");
set.add("ulike");
set.add("love");
set.add("today");
System.out.println(set);
}
public static void bjqDemo2() {
TreeSet<Integer> set=new TreeSet<>(new ComInt());//因为比较器的优先级高于天然比较性
set.add(10);
set.add(12);
set.add(1);
set.add(20);
set.add(30);
set.add(990);
set.add(17);
System.out.println(set);
}
public static void bjqDemo1() {
TreeSet<Integer> set=new TreeSet<>();
set.add(10);
set.add(12);
set.add(1);
set.add(20);
set.add(30);
set.add(990);
set.add(17);
System.out.println(set);
}
}
package com.qf.set2;
import java.util.Comparator;
public class ComInt implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
return o2.compareTo(o1);
}
}
package com.qf.set2;
import java.util.Comparator;
public class ComString implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
// TODO Auto-generated method stub
//长度是主要条件 当长度相等时 按找字典顺序再比较
int lengthVs = o1.length()-o2.length();
if (lengthVs == 0) {
return o1.compareTo(o2);
}
return lengthVs;
}
}
十、Map
Map分为:
HashMap取代了HashTable
- HashMap – 线程不同步,速度快,不安全
- HashTable–线程同步,速度慢,安全
TreeMap
Map<K,V> 键值对 ,键唯一、值随便,双列集合
- key 只能是 set – set有两种 HashSet和TreeSet(K – 表示键的类型,可以是自定义类型 V – 表示值得类型,可以是自定义类型)
- 如果键是HashSet,那么就是HashMap – 只在乎唯一
- 如果键是TreeMap,那么就是TreeMap – 不仅在乎唯一还在乎顺序
- value 是 collection
1.Map的增删改查和遍历
添加
.put(key,value)
– 没有就添加,有了就是修改将一个map添加到一个map中 :
.putAll(map)
大小:
.size()
根据键获取值得方法
.get(key)
判断是否含有某个键
.containsKey(key)
判断包含不包含某个值
.containsValue(value)
判断是否为空:
.isEmpty()
根据键删除:
.remove(key)
得到所有的值:
.values()
Map的遍历
- 获取所有键再去获取所有值
- 使用
.keySet
方法拿到所有的key,再用.get(key)
就可以找到值- 获取Map的映射关系,然后获取键和值
- 使用
.entrySet
获取到映射关系就是一个set集合,然后再遍历.getKey
.getValue
package com.qf.map1;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import com.sun.org.apache.xalan.internal.xsltc.compiler.sym;
public class DemoMap1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap<String, String> map = new HashMap<>();
System.out.println("++++++++++++增删改查========");
map.put("001", "宋江");
map.put("002", "卢俊义");
map.put("003", "吴用");
map.put("004", "林冲");
System.out.println(map);
System.out.println(map.size());
System.out.println("===根据键获取值===");
String name1 = map.get("003");
System.out.println(name1);
System.out.println("===判断是否含有某个键====");
System.out.println("===是否含有001?=="+map.containsKey("001")+":"+map.get("001"));
System.out.println("====判断有没有某一个值====");
String name2="武松";
System.out.println("有诶有武松?"+map.containsValue(name2));
System.out.println(map.isEmpty());
HashMap<String, String> map2=new HashMap<>();
map2.put("008", "武松");
map2.put("009", "李逵");
System.out.println(map2);
map.putAll(map2);
System.out.println(map);
String key = "009";
String remove = map.remove(key);
System.out.println(remove);
System.out.println(map);
Collection<String> values = map.values();
Iterator<String> iterator = values.iterator();
while (iterator.hasNext()) {
String string = (String) iterator.next();
System.out.print(string+",");
}
System.out.println();
map.put("001", "晁盖");
System.out.println(map);
System.out.println("=========map的遍历方式有两种 一种获取所有键 再去获取所有值====");
Set<String> keySet = map.keySet();
Iterator<String> iterator2 = keySet.iterator();
while (iterator2.hasNext()) {
String key1 = (String) iterator2.next();
//根据键获取值
String value = map.get(key1);
System.out.println(key1+"------"+value);
}
System.out.println("=====先获取map的映射关系 然后获取键和值====");
Set<Entry<String, String>> entrySet = map.entrySet();//获取所有的映射关系
for (Entry<String, String> entry : entrySet) {
String key2 = entry.getKey();
String value = entry.getValue();
System.out.println(key2+":::::::::"+value);
}
}
}
1.2 学生类做键
package com.qf.map1;
public class Student implements Comparable<Student>{
private String name;
private int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
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 + "]";
}
@Override
public int compareTo(Student o) {
// TODO Auto-generated method stub
System.out.println(this+"======"+o);
int ageVs = this.age-o.age;
if (ageVs == 0) {
return this.name.compareTo(o.name);
}
return ageVs;
}
}
package com.qf.map1;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
public class TestMap1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//当一个自定义对象想存储到HashMap当中 必须保证其唯一性 实现hashcode equals
HashMap<Student, String> map=new HashMap<>();
map.put(new Student("宋江", 20), "祁县");
map.put(new Student("宋江", 20), "长安县");
map.put(new Student("晁盖", 30), "高陵");
map.put(new Student("吴用", 20), "临潼");
System.out.println(map);
System.out.println("++++++++++++++++");
Set<Student> keySet = map.keySet();
for (Student student : keySet) {
String jiguan = map.get(student);
System.out.println(student+"===="+jiguan);
}
System.out.println("+++++++++++++++++++++++++++");
Set<Entry<Student, String>> entrySet = map.entrySet();
for (Entry<Student, String> entry : entrySet) {
Student key = entry.getKey();
String value = entry.getValue();
System.out.println(key+":::::::::::"+value);
}
}
}
1.3 TreeSet的比较过程
package com.qf.map2;
import java.util.Comparator;
import com.qf.map1.Student;
public class ComStudent implements Comparator<Student> {
@Override
public int compare(Student stu1, Student stu2) {
// TODO Auto-generated method stub
return stu2.compareTo(stu1);
}
}
package com.qf.map2;
import java.util.Set;
import java.util.TreeMap;
import com.qf.map1.Student;
public class DemoTreeMap {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Treeset
fun2();
}
public static void fun2() {
TreeMap<Student, String> map=new TreeMap<>(new ComStudent());
map.put(new Student("宋江", 20), "雁塔");// com.qf.map1.Student cannot be cast to java.lang.Comparable
map.put(new Student("吴用",22), "铜川");
map.put(new Student("武松", 30), "渭南");
map.put(new Student("李逵", 18), "宝鸡");
System.out.println("++++++++++++++++++++");
Set<Student> keySet = map.keySet();
for (Student student : keySet) {
String jiguan = map.get(student);
System.out.println(student+"===="+jiguan);
}
}
public static void fun1() {
TreeMap<Student, String> map=new TreeMap<>();
map.put(new Student("宋江", 20), "雁塔");// com.qf.map1.Student cannot be cast to java.lang.Comparable
map.put(new Student("吴用",22), "铜川");
map.put(new Student("武松", 30), "渭南");
map.put(new Student("李逵", 18), "宝鸡");
System.out.println("++++++++++++++++++++");
Set<Student> keySet = map.keySet();
for (Student student : keySet) {
String jiguan = map.get(student);
System.out.println(student+"===="+jiguan);
}
}
}
package com.qf.map2;
import java.util.TreeSet;
import com.qf.map1.Student;
public class TestBiJIao {
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeSet<Student> students =new TreeSet<>();
students.add(new Student("宋江", 20));
students.add(new Student("晁盖",30));
students.add(new Student("李逵", 10));
students.add(new Student("燕青", 17));
students.add(new Student("林冲", 32));
students.add(new Student("阮小七", 25));
students.add(new Student("时迁", 36));
for (Student student : students) {
System.out.println(student);
}
}
}
1.4 面试题:给定一个字符串"aksksjjdjkadfa" 获取每个字母出现的次数打印结果 a(1)b(2)c(4)…
package com.qf.map2;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
public class TestZiMuCount {
public static void main(String[] args) {
// TODO Auto-generated method stub
//"aksksjjdjkadfa" 获取每个字母出现的次数
//打印结果 a(1)b(2)c(4)...
//map----Treemap
// Character Integer
TreeMap<Character, Integer> map=new TreeMap<>();
String string="aksksjjdjkadfa";
//手先将字符串转换成字符数组
char[] charArray = string.toCharArray();
for (char c : charArray) {
//c---字母
//判断map之前是否存储过这个字母
//如果有 次数加加 没有就存字母一次
int count =1;
if (map.containsKey(c)) {
count = map.get(c);
count++;
}
map.put(c, count);
}
System.out.println(map);
Set<Entry<Character, Integer>> entrySet = map.entrySet();
for (Entry<Character, Integer> entry : entrySet) {
Character zimu = entry.getKey();
Integer count = entry.getValue();
System.out.print(zimu+"("+count+")");
}
System.out.println();
}
}
十一、IO流
读和写
写:写刷关
读:读关
io流
- 字符流
- 读 – 输入-- (Reader 、FileReader)
- 写 – 输出–(Writer、FileWriter )
- 字节流
- 读 – 输入流(InputStream、FileInputStream)
- 写 – 输出流(OutputStream、FileOutputStream)
1.字符流
1.1写、续写、读
package com.qf.zifuliu;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class XieDemo {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
du2();
}
private static void du2() throws IOException{
// TODO Auto-generated method stub
FileReader fileReader=new FileReader("D:\\2202\\day59\\uu.txt");
char[] cs=new char[3];
int len=0;//每次读到多少个字符
/*int read = fileReader.read(cs);
System.out.println(new String(cs));
read = fileReader.read(cs);
System.out.println(new String(cs));*/
while ((len=fileReader.read(cs))!=-1) {
System.out.print(new String(cs, 0, len));
}
System.out.println();
}
public static void du() throws IOException{
FileReader fileReader=new FileReader("D:\\2202\\day59\\uu.txt");
/*int read = fileReader.read();
System.out.println((char)read);
read = fileReader.read();
System.out.println((char)read);
read = fileReader.read();
System.out.println((char)read);*/
int result = 0;
while ((result=fileReader.read())!=-1) {//先赋值 后判断
System.out.print((char)result);
}
System.out.println();
}
public static void xie() throws IOException{
FileWriter fileWriter=new FileWriter("D:\\2202\\day59\\uu.txt");
//写刷关
fileWriter.write("hello world");
fileWriter.write("killer is uu", 0, 6);//接着上面的写,写前五个字符
fileWriter.write(97);//97就是小写的a
fileWriter.flush();
fileWriter.close();
System.out.println("=====over=====");
FileWriter fileWriter2=new FileWriter("D:\\2202\\day59\\uu.txt",true);//文件的续写
fileWriter2.write(" xuxie");
fileWriter2.flush();
fileWriter2.close();
System.out.println("====续写成功====");
}
}
复制
package com.qf.zifuliu;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class XieDemo {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//du2();
//copy("D:\\2202\\day59\\Map-作业.txt", "D:\\2202\\day59\\Map9999.txt");
copy2("D:\\2202\\day59\\Map-作业.txt", "D:\\2202\\day59\\Map2222.txt");
}
//使用增强流来进行复制
private static void copy2(String fileold,String filenew) throws IOException {
FileReader fileReader=new FileReader(fileold);
FileWriter fileWriter=new FileWriter(filenew);
BufferedReader bufferedReader=new BufferedReader(fileReader);
BufferedWriter bufferedWriter=new BufferedWriter(fileWriter);
String hang="";
while ((hang=bufferedReader.readLine())!=null) {//readLine---只读行内的内容不读回车符
bufferedWriter.write(hang);
bufferedWriter.newLine();//换行
bufferedWriter.flush();
}
bufferedReader.close();
bufferedWriter.close();
System.out.println("===copy over===");
}
//文本文件的复制
private static void copy(String fileold,String filenew) throws IOException{
FileReader fileReader=new FileReader(fileold);
FileWriter fileWriter=new FileWriter(filenew);
char[] cbuf=new char[1024];
int len=0;
while ((len=fileReader.read(cbuf))!=-1) {
fileWriter.write(cbuf, 0, len);
fileWriter.flush();
}
fileReader.close();
fileWriter.close();
System.out.println("===拷贝成功===");
}
private static void du3() throws IOException{
// TODO Auto-generated method stub
FileReader fileReader=new FileReader("D:\\2202\\day59\\Map-作业.txt");
char[] cs=new char[1024];
int len=0;//每次读到多少个字符
/*int read = fileReader.read(cs);
System.out.println(new String(cs));
read = fileReader.read(cs);
System.out.println(new String(cs));*/
while ((len=fileReader.read(cs))!=-1) {
System.out.print(new String(cs, 0, len));
}
System.out.println();
}
2. 字节流
package com.qf.zijieliu;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CaoZuoDemo {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//xieTest();
//duTest2();
//copy1("D:\\2202\\day59\\Map9999.txt", "D:\\2202\\day59\\Map888.txt");
copy1("D:\\2202\\day59\\一对多关系.png", "D:\\2202\\day59\\xxx.jpg");
}
//字节流的拷贝
public static void copy1(String fileold,String filenew) throws IOException {
FileOutputStream fileOutputStream=new FileOutputStream(filenew);
FileInputStream fileInputStream=new FileInputStream(fileold);
//一边读 一边写
//
byte[] cbuf = new byte[1024];
int len=0;//每次读到的长度
while ((len=fileInputStream.read(cbuf))!=-1) {
fileOutputStream.write(cbuf, 0, len);
fileOutputStream.flush();
}
fileInputStream.close();
fileOutputStream.close();
System.out.println("====copy===over===");
}
//读到字节数组
public static void duTest2() throws IOException{
FileInputStream fileInputStream=new FileInputStream("D:\\2202\\day59\\Map9999.txt");
byte[] cbuf = new byte[1024];
int len=0;//每次读到多少个字节
while ((len=fileInputStream.read(cbuf))!=-1) {
System.out.print(new String(cbuf, 0, len));
}
fileInputStream.close();
}
//字节流的读---一个一个读
public static void duTest() throws IOException{
FileInputStream fileInputStream=new FileInputStream("D:\\2202\\day59\\zijie.txt");
/*int read = fileInputStream.read();
System.out.println((char)read);
read = fileInputStream.read();
System.out.println((char)read);*/
int result = 0;
while ((result=fileInputStream.read())!=-1) {
System.out.print((char)result);
}
System.out.println();
fileInputStream.close();
}
//字节流的写
public static void xieTest() throws IOException{
FileOutputStream fileOutputStream=new FileOutputStream("D:\\2202\\day59\\zijie.txt");
fileOutputStream.write(97);
fileOutputStream.write("hello world".getBytes());
fileOutputStream.flush();
System.out.println("++++++over===");
fileOutputStream.close();
}
}
3. 文件
package com.qf.wenjian;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class DemoFile {
public static void main(String[] args) throws IOException {
// TODO File这个文件类
getAllFiles(new File("D:\\2202\\day59"));
}
//文件夹的递归遍历
public static void getAllFiles(File file) throws IOException{
if (file.isFile()) {
System.out.println("====不是目录===");
return;
}
if (!file.exists()) {
System.out.println("===此目录不存在====");
}
//是目录而且存在
File[] listFiles = file.listFiles();//获取这个文件夹下所有的文件及文件夹
for (File file2 : listFiles) {
if (file2.isFile()) {
if (file2.getName().endsWith(".png")) {
System.out.println(file2);
}
} else {
getAllFiles(file2);
}
}
}
public static void fun1() throws IOException{
System.out.println(File.pathSeparator);
System.out.println(File.pathSeparatorChar);
System.out.println(File.separator);
System.out.println(File.separatorChar);
File file=new File("D:\\2202\\day59\\kk");
boolean mkdir = file.mkdir();//创建文件夹
if (mkdir) {
System.out.println("+++创建文件夹成功+++");
}
File file2=new File(file, "cc");
boolean mkdir2 = file2.mkdir();
System.out.println(mkdir2);
File file3=new File(file, "killer.txt");
boolean createNewFile = file3.createNewFile();//创建一个文件
System.out.println(createNewFile);
FileWriter fileWriter=new FileWriter(file3);//使用文件创建一个文件流
fileWriter.write("sdjjdfshdsf sdadsfaah sadhhsdafhhfd");//使用文件流给文件写内容
fileWriter.flush();
fileWriter.close();
File file4=new File(file2, "qq.txt");
boolean createNewFile2 = file4.createNewFile();
System.out.println(createNewFile2);
FileWriter fileWriter2=new FileWriter(file4);
fileWriter2.write("killer is comming");
fileWriter2.flush();
fileWriter2.close();
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-DjWYnmep-1679826670011)(C:\Users\11700\AppData\Roaming\Typora\typora-user-images\image-20220601102807217.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GnS8Zz8q-1679826670011)(C:\Users\11700\AppData\Roaming\Typora\typora-user-images\image-20220601103400635.png)]
4.线程 – Thread
sleep():休眠,时间到就醒了
wait():等待 — 需要别人来叫醒 (notify())
notifyAll() – 把别人都叫醒
interrupt()-- 中断 – 砸醒睡的和等待的
死锁 – 就是抢夺资源 互不相让
package duoxiancheng;
public class MyTheard extends Thread {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+"==="+i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package duoxiancheng;
public class Demo implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName()+"+++"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package duoxiancheng;
public class XianChengDemo {
public static void main(String[] args) {
System.out.println("====主线程====");
System.out.println(Thread.currentThread().getName()+"---");
System.out.println("========================");
MyTheard myTheard = new MyTheard();
myTheard.start();//开启一个子线程
System.out.println("----------------------------");
Demo demo = new Demo();
Thread thread= new Thread(demo);
thread.start();//开启另外一个子线程
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName()+"&&&&&"+i);
Thread.sleep(1000);
}
}
}
十二、单元测试(Junit)
对类和方法的测试
junit :单元测试框架
测试过程:
@BeforClass:所有用例执行之前-- 对应函数名为 setUpBeforeClass()
@AfterClass:所有用例执行之后 – 对应函数名为 tearDownAfterClass()
@Befor:每一个测试方法之前 – 对应函数名为 setUp()
@After:每个测试方法之后 – 对应函数名为 tearDown()
@Test:每个测试方法之前-- 意思是说这是一个单元测试方法
@Ignore:忽略此方法,不执行
断言测试–assertXXX:实际结果和预期结果是否一致
1.断言
assertEquals:判断两个结果是否相等
assertArrayEquals:判断两个数组是否相等
assertTrue():预期结果是真,实际结果应该是布尔值
assertFalse:期望结果是假的
assertNull:期望结果为空
assertNotNull:期望结果为非空
assertSame: 期望地址相同
assertThise:–不要求
fail:天然失败的断言,一般会用到try – catch的catch中
package gongneng;
public class User {
private String uname;
private String upw;
public User(String uname, String upw) {
super();
this.uname = uname;
this.upw = upw;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUpw() {
return upw;
}
public void setUpw(String upw) {
this.upw = upw;
}
@Override
public String toString() {
return "User [uname=" + uname + ", upw=" + upw + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((uname == null) ? 0 : uname.hashCode());
result = prime * result + ((upw == null) ? 0 : upw.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (uname == null) {
if (other.uname != null)
return false;
} else if (!uname.equals(other.uname))
return false;
if (upw == null) {
if (other.upw != null)
return false;
} else if (!upw.equals(other.upw))
return false;
return true;
}
}
package gongneng;
public class JiSuan {
public static int add(int a,int b) {
return a+b;
}
}
package gongneng;
public class Person {
private String name;
private int age;
public Person(String name, int age) {
super();
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 "Person [name=" + name + ", age=" + age + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
package gongneng;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class GongNengDemo {
public static boolean contains(String string,String zichuan) {
if (string.contains(zichuan)) {
return true;
} else {
return false;
}
}
public static boolean mapTest(HashMap<String, String> map,String key) {
if (map.containsKey(key)) {
return true;
} else {
return false;
}
}
public static List<String> getList(int type) {
List<String> list=new ArrayList<>();
switch (type) {
case 1:
list.add("hello");
break;
case 2:
list.add("killer");
break;
default:
list = null;
break;
}
return list;
}
public boolean login(String uname,String upw) {
ArrayList<User> users=new ArrayList<>();
users.add(new User("qq", "123"));
users.add(new User("张飞", "222"));
users.add(new User("吕布", "999"));
users.add(new User("张辽", "666"));
users.add(new User("张郃", "888"));
User user=new User(uname, upw);
if (users.contains(user)) {
return true;
}
return false;
}
public static Person getPerson(int id) {
if (id==1) {
return new Person("张飞", 20);
} else {
return new Person("关羽",22);
}
}
public static int[] getArray(int type) {
int[] arr1={1,2,3};
int[] arr2={2,3,4};
if (type == 1) {
return arr1;
} else {
return arr2;
}
}
}
package gongneng;
import static org.junit.Assert.*;
import java.util.HashMap;
import org.junit.Test;
public class TestCAse {
@Test
public void testMap(){
HashMap<String, String> map = new HashMap<>();
map.put("001", "宋江");
map.put("002", "阎婆惜");
map.put("003", "阮小七");
map.put("004", "晁盖");
String key = "001";
boolean mapTest = GongNengDemo.mapTest(map, key);
assertTrue(mapTest);
}
@Test
public void testSame(){
int num = 13;
int num1 = 13;
assertSame(num, num1);
}
@Test
public void testNull(){
java.util.List<String> list = GongNengDemo.getList(0);
assertNotNull(list);
}
@Test
public void testLogin(){
boolean login = new GongNengDemo().login("张郃","888");
//assertTrue("登陆失败", login);//assertTrue---期望结果是真的
assertFalse("登陆成功", login);//assertFalse--期望结果是假的
}
@Test
public void test04() {
int[] expected = {7,8,9};
int[] actual =GongNengDemo.getArray(1);
assertArrayEquals("返回的数组不正确", expected, actual);
}
@Test
public void test03(){
Person expected=new Person("关羽", 22);
Person actual = GongNengDemo.getPerson(1);
assertEquals("测试失败了", expected, actual);
}
@Test
public void test02(){
assertEquals("测试失败了", "hello", "hello");
}
@Test
public void test() {
Person expected=new Person("张飞", 20);
Person actual=new Person("张飞", 20);
assertEquals(expected, actual);
}
}
2.测试套件
Suite–套件的意思
@RunWith注解–修改测试运行器,例如@RunWith(Suite.class),这个类就成为套件的入口类
@SuiteClasses()中放入测试套件的测试类,以数组的形式{class1,class2}作为参数
package com.qf.test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({ TestCase01.class, Testcase03.class, TestCase2.class })
public class AllTests {
/*
* * 1.测试套件就是组织测试类一起运行的
* 写一个作为测试套件的入口类,这个类里不包含其他的方法
* 更改测试运行器Suite.class
* 将要测试的类作为数组传入到Suite.SuiteClasses({})
*/
}
package com.qf.test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({TestCase01.class,TestCase2.class})
public class MyTestSuit {
}
package com.qf.test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({ TestCase01.class, Testcase03.class })
public class MySuit3 {
}
3.参数化
@RunWith(Parameterized.class)注解–改变默认运行器,以参数化的
@Parameters 注解
package com.qf.canshuhua;
public class BeiCeClass {
public static int add(int a,int b) {
return a+b;
}
}
package com.qf.canshuhua;
import java.util.Arrays;
import java.util.Collection;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class CanShuHua {
private int expected = 0;
private int input1=0;
private int input2 = 0;
public CanShuHua(int expected, int input1, int input2) {
super();
this.expected = expected;
this.input1 = input1;
this.input2 = input2;
}
@Parameters
public static Collection<Object[]> data(){
return Arrays.asList(new Object[][]{{9,4,5},{10,2,8},{8,3,5},{9,3,6},{18,2,6}});
//[{},{},{}]
}
@Test
public void testAdd(){
int actual = BeiCeClass.add(input1, input2);
assertEquals("预期与实际结果不符",expected, actual);
}
}
package com.qf.canshuhua2;
public class YongHu {
private String uname;
private String upw;
public YongHu(String uname, String upw) {
super();
this.uname = uname;
this.upw = upw;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUpw() {
return upw;
}
public void setUpw(String upw) {
this.upw = upw;
}
@Override
public String toString() {
return "YongHu [uname=" + uname + ", upw=" + upw + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((uname == null) ? 0 : uname.hashCode());
result = prime * result + ((upw == null) ? 0 : upw.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
YongHu other = (YongHu) obj;
if (uname == null) {
if (other.uname != null)
return false;
} else if (!uname.equals(other.uname))
return false;
if (upw == null) {
if (other.upw != null)
return false;
} else if (!upw.equals(other.upw))
return false;
return true;
}
}
package com.qf.canshuhua2;
import java.util.ArrayList;
public class Login {
public static boolean login(String uname,String upw) {
YongHu yongHu=new YongHu(uname, upw);
ArrayList<YongHu> yongHus=new ArrayList<>();
yongHus.add(new YongHu("qq", "123"));
yongHus.add(new YongHu("uu", "888"));
yongHus.add(new YongHu("killer", "000"));
yongHus.add(new YongHu("ss", "sss"));
yongHus.add(new YongHu("kk", "123"));
if (yongHus.contains(yongHu)) {
System.out.println("+++++++++++++"+uname);
return true;
}
return false;
}
}
package com.qf.canshuhua2;
import java.util.Arrays;
import java.util.Collection;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class TestLogin {
//uname upw islogin
boolean isLogin;
String uname;
String upw;
public TestLogin(boolean isLogin, String uname, String upw) {
super();
this.isLogin = isLogin;
this.uname = uname;
this.upw = upw;
}
@Parameters
public static Collection<Object[]> data(){
return Arrays.asList(new Object[][]{{
true,"qq","123"
},{
true,"ww","999"
},{
true,"uu","888"
},{
true,"killer","000"
},{
true,"kk","888"
},{
true,"ss","sss"
}});
}
@Test
public void testLogin(){
boolean actual = Login.login(uname, upw);
assertEquals("不能登陆用户名或者密码错误", isLogin, actual);
}
}
4.可变参数
package com.qf.canshuhua;
import java.util.Arrays;
import java.util.List;
public class KeBianCanShu {
public static void main(String[] args) {
// TODO Auto-generated method stub
int add = add(1,2,3);
System.out.println(add);
int add2 = add(1,1,1,1,1,1);
System.out.println(add2);
System.out.println("+++++++++++++++=");
List<Integer> asList = Arrays.asList(1,2,3,4);
System.out.println(asList);
System.out.println("++++++++++++++++++++++++");
int[] arr1 = new int[]{1,2,3};
int[][] arr=new int[][]{{},{},{}};
}
public static int addx(int a,int b) {
return a+b;
}
public static int addx(int a,int b,int c) {
return a+b+c;
}
public static int add(int... a) {//可变参数
//System.out.println(a);//[I@659e0bfd
//System.out.println(a.length);
int sum=0;
for (int i : a) {
sum+=i;
}
return sum;
}
}
api
重点:
怎么写断言–测试套件—参数化
5.<> – 这个尖括号一出现就是指泛型
6.Arrary.asList() – 为什么能用 类.方法 ,因为这个方法是静态方法
7.fail() – 失败的断言,出现fail肯定会失败
8.如何测试异常
@Test(expected = Exception.class) – 期望=异常的类型,不知道是什么异常就可以用父类 Exception.class
@Test(expected = NullPointerException.class)
publicvoid passwordIsNullThrowsException() throwsInvalidPasswordException{
Password.validate(null) }
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({ TestCase01.class, Testcase03.class, TestCase2.class })
public class AllTests {
/*
-
-
1.测试套件就是组织测试类一起运行的
-
写一个作为测试套件的入口类,这个类里不包含其他的方法
-
更改测试运行器Suite.class
-
将要测试的类作为数组传入到Suite.SuiteClasses({})
*/
}
-
```java
package com.qf.test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({TestCase01.class,TestCase2.class})
public class MyTestSuit {
}
package com.qf.test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({ TestCase01.class, Testcase03.class })
public class MySuit3 {
}
3.参数化
@RunWith(Parameterized.class)注解–改变默认运行器,以参数化的
@Parameters 注解
package com.qf.canshuhua;
public class BeiCeClass {
public static int add(int a,int b) {
return a+b;
}
}
package com.qf.canshuhua;
import java.util.Arrays;
import java.util.Collection;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class CanShuHua {
private int expected = 0;
private int input1=0;
private int input2 = 0;
public CanShuHua(int expected, int input1, int input2) {
super();
this.expected = expected;
this.input1 = input1;
this.input2 = input2;
}
@Parameters
public static Collection<Object[]> data(){
return Arrays.asList(new Object[][]{{9,4,5},{10,2,8},{8,3,5},{9,3,6},{18,2,6}});
//[{},{},{}]
}
@Test
public void testAdd(){
int actual = BeiCeClass.add(input1, input2);
assertEquals("预期与实际结果不符",expected, actual);
}
}
package com.qf.canshuhua2;
public class YongHu {
private String uname;
private String upw;
public YongHu(String uname, String upw) {
super();
this.uname = uname;
this.upw = upw;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUpw() {
return upw;
}
public void setUpw(String upw) {
this.upw = upw;
}
@Override
public String toString() {
return "YongHu [uname=" + uname + ", upw=" + upw + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((uname == null) ? 0 : uname.hashCode());
result = prime * result + ((upw == null) ? 0 : upw.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
YongHu other = (YongHu) obj;
if (uname == null) {
if (other.uname != null)
return false;
} else if (!uname.equals(other.uname))
return false;
if (upw == null) {
if (other.upw != null)
return false;
} else if (!upw.equals(other.upw))
return false;
return true;
}
}
package com.qf.canshuhua2;
import java.util.ArrayList;
public class Login {
public static boolean login(String uname,String upw) {
YongHu yongHu=new YongHu(uname, upw);
ArrayList<YongHu> yongHus=new ArrayList<>();
yongHus.add(new YongHu("qq", "123"));
yongHus.add(new YongHu("uu", "888"));
yongHus.add(new YongHu("killer", "000"));
yongHus.add(new YongHu("ss", "sss"));
yongHus.add(new YongHu("kk", "123"));
if (yongHus.contains(yongHu)) {
System.out.println("+++++++++++++"+uname);
return true;
}
return false;
}
}
package com.qf.canshuhua2;
import java.util.Arrays;
import java.util.Collection;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class TestLogin {
//uname upw islogin
boolean isLogin;
String uname;
String upw;
public TestLogin(boolean isLogin, String uname, String upw) {
super();
this.isLogin = isLogin;
this.uname = uname;
this.upw = upw;
}
@Parameters
public static Collection<Object[]> data(){
return Arrays.asList(new Object[][]{{
true,"qq","123"
},{
true,"ww","999"
},{
true,"uu","888"
},{
true,"killer","000"
},{
true,"kk","888"
},{
true,"ss","sss"
}});
}
@Test
public void testLogin(){
boolean actual = Login.login(uname, upw);
assertEquals("不能登陆用户名或者密码错误", isLogin, actual);
}
}
4.可变参数
package com.qf.canshuhua;
import java.util.Arrays;
import java.util.List;
public class KeBianCanShu {
public static void main(String[] args) {
// TODO Auto-generated method stub
int add = add(1,2,3);
System.out.println(add);
int add2 = add(1,1,1,1,1,1);
System.out.println(add2);
System.out.println("+++++++++++++++=");
List<Integer> asList = Arrays.asList(1,2,3,4);
System.out.println(asList);
System.out.println("++++++++++++++++++++++++");
int[] arr1 = new int[]{1,2,3};
int[][] arr=new int[][]{{},{},{}};
}
public static int addx(int a,int b) {
return a+b;
}
public static int addx(int a,int b,int c) {
return a+b+c;
}
public static int add(int... a) {//可变参数
//System.out.println(a);//[I@659e0bfd
//System.out.println(a.length);
int sum=0;
for (int i : a) {
sum+=i;
}
return sum;
}
}
api
重点:
怎么写断言–测试套件—参数化
5.<> – 这个尖括号一出现就是指泛型
6.Arrary.asList() – 为什么能用 类.方法 ,因为这个方法是静态方法
7.fail() – 失败的断言,出现fail肯定会失败
8.如何测试异常
@Test(expected = Exception.class) – 期望=异常的类型,不知道是什么异常就可以用父类 Exception.class
@Test(expected = NullPointerException.class)
publicvoid passwordIsNullThrowsException() throwsInvalidPasswordException{
Password.validate(null) }