//单行注释
/*
多行注释
*/
/**
文档注释,可提取到文档
*/
快捷键:
ctrl+/单行注释
ctrl+shiift+/ 取消注释
补充:注释内容编译时会直接跳过
//字符:单引号''括起来,有且只能有一个字符
'a'//字符内容为字母a
' '//字符内容为空格
''//报错
'\n'//换行
'\t'//代表一个tab
//字符串:双引号""括起来,内容无要求
"123aB种"
""
int a = 1;
{
a = 2;//再次定义变量a属于重复,函数内自上而下执行(反之,若{int a = 1;} int a;可以)
System.out.println(a);
}
System.out.println(a);
{
int b = 1;
System.out.println(b);
}
{
int b = 2;//变量b是局部变量
System.out.println(b);
}
字面量,常量和变量三者间的对比:
字面量是指由字母,数字等构成的字符串或者数值,它只能作为右值出现,(右值是指等号右边的值,如:int a=123这里的a为左值,123为右值。)
常量和变量都属于变量,只不过常量是赋过值后不能再改变的变量(类似于只读文件),而普通的变量可以再进行赋值操作。
short s1 = 1, s2 = 2;
//short s3 = s1 + s2;报错,接受为short,提供的为int
int s3 = s1 + s2;
short s4 = (short)(s1 + s2);
int i = 5;
char c = 'A';
System.out.println(i + 'A');//70
System.out.println(c + 5);//70
int d = c;
System.out.println(d + 5);//70
* 强制类型转换
a += b;
等价于:
a = (a的类型)(a + b);
即+=之类的赋值操作,自带强制转换
* 算术运算符+,-,*,/,%
int a = 10, b = 3;
System.out.println(10/3);//3
System.out.println(10.0/3);//3.3333333333333335
System.out.println(a * 1.0 / b);//3.3333333333333335
System.out.println(a / b);//3两个整数相除的结果是整数(直接舍弃小数部分)
System.out.println(-1 % 5);//-1
System.out.println(-5 % 5);//0
int e = 5;
char c1 = 'A';
System.out.println(e + "hahaha");//5hahaha 不能算,直接连接
System.out.println(e + c1 + "hahaha");//70hahaha 前两者能算,后面不能算直接连接
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
switch (n){
case 1 :
case 2:
case 3:
case 4:
case 5:
System.out.println("finish the tasks at hand!");
break;
case 6:
case 7:
System.out.println("enhance algorithm, codding and cet-6!");
break;
default:
System.out.println("input is error~");
}
int[] ages = new int[]{25, 26,27};//静态初始化
int[] month = {7, 8, 9};//简化版,初始化
int day[] = {11, 12, 13};//语法上也可以,但不推荐。因为前者更容易看出来是某类型的数组,可读性更好
System.out.println(ages);//[I@4eec7777
System.out.println(money);//[D@3b07d329
System.out.println(ages.length);//3
System.out.println(ages[0]);//25,数组索引从0开始
//简单应用1:找数组最大值
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int[] score = new int[10];
int max = -1;
for(int i = 0; i < score.length; i++)
score[i] = sc.nextInt();
for (int i = 0; i < score.length; i++) {
if(score[i] > max) max = score[i];
}
System.out.println(max);
}
//简单应用2:反转数组
public static void main(String[] args){
int[] score = new int[]{1, 2, 3, 4, 5, 6};
/*for(int i = 0, j = score.length - 1; i < j; i++, j--){
int temp = score[i];
score[i] = score[j];
score[j] = temp;
}*/
for(int i = 0; i < score.length / 2; i++){
int temp = score[i];
score[i] = score[score.length - i - 1];
score[score.length - i - 1] = temp;
}
for (int i = 0; i < score.length; i++) {
System.out.print(" " + score[i]);
}
}
方法命名规范:首字母以小写开头,每个单词首字母大写(第一个单词除外)。最好是一个动词或者动词词组或者第一个单词为一个动词。如:getUserName()
//简单应用:1~n求和,用方法实现
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println(sum(n));
}
public static int sum(int n){
int sum = 0;
for(int i = 1; i <= n; i++){
sum += i;
}
return sum;
}
方法在栈内存中运行,以保证一个方法调用完另一个方法后可以回来。
方法参数传递
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int[] a = new int[8];
for(int i = 0; i < 8; i++)
a[i] = sc.nextInt();
print(a);
}
static void print(int[] n){
if(n == null) System.out.println(n);
System.out.print("[");
for(int i = 0; i < n.length; i++){
System.out.print(n[i]);
if(i != n.length - 1)
System.out.print(",");
}
System.out.print("]");
}
//简单综合应用:生成验证码
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println(CreateCode(n));
}
public static String CreateCode(int n){
String code = "";
int m;
Random r = new Random();
for(int i = 0; i < n; i++){
m = r.nextInt(3);
switch(m){
case 0 :
code += r.nextInt(10);
break;
case 1 :
code += (char)(r.nextInt(26) + 65);
break;
case 2 :
code += (char)(r.nextInt(26) + 97);
// char c = (char)(r.nextInt(26) + 97);
// code += c;
break;
}
}
return code;
}
//简单综合运用:评委打分,去掉最高和最低分取平均分
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();//评委人数
score(n);
}
public static void score(int n){
int[] grade = new int[n];
int max = -1, min = 101, sum = 0;//分数范围0~100,打分规则去掉最高分和最低分求平均分
Scanner sc = new Scanner(System.in);
for(int i = 0; i < n; i++){
grade[i] = sc.nextInt();
if(grade[i] > max) max = grade[i];
if(grade[i] < min) min = grade[i];
sum += grade[i];
}
System.out.println(1.0 * (sum - min - max) / (n - 2));
}
//需求:对所给年份加密,每位数字先加5再对10求余,最后翻转处理后的每位数字
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int year = sc.nextInt();
int[] result = encode(year);
for(int i = 0; i < result.length; i++)
System.out.print(result[i]);
}
public static int[] encode(int n){
int[] nums = split(n);
for(int i = 0; i < 4; i++)
nums[i] = (nums[i] + 5) % 10;
reverse(nums);
return nums;
}
public static int[] split(int n){
int[] ans = new int[4];
for(int i = 0; i < 4; i++){
ans[i] = n % 10;
n /= 10;
}
return ans;
}
public static void reverse(int[] a){
for(int i = 0; i < a.length / 2; i++){
int t = a[i];
a[i] = a[a.length - 1 - i];
a[a.length - 1 - i] = t;
}
}
//打印乘法表
public static void main(String[] args) {
for(int i = 1; i < 10; i++){
for(int j = 1; j <= i; j++){
System.out.print(j + "x" + i + '=' + i*j + '\t');
}
System.out.println();
}
}
public class HelloObject {
public static void main(String[] args) {
Student s1 = new Student();
s1.setScore(100);
StudentOperator so = new StudentOperator();
if(so.isPass(s1, 60)) System.out.println("Passed");
else System.out.println("No Pass");
}
}
public class Student {
private String name;
private double score;
public Student() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
}
public class StudentOperator {
public boolean isPass(Student student, double score){
if(student.getScore() > score) return true;
return false;
}
}
String s1 = "222";//第二种构造方法建议转化为该方式初始化
System.out.println(s1);
byte[] b = {65, 67, 98};
String s2 = new String(b);
System.out.println(s2);//ACb
String s3 = "abcde", s4 = "abcde", s5 = new String(s3);
System.out.println(s3.charAt(4));//字符串.charAt(index)取字符串中指定索引的字符
System.out.println(s3 == s4);//true 直接比较的比较内容是指向的地址是否相同
System.out.println(s3 == s5);//false s3和s5没有指向同一个对象,非字符串内容的比较
System.out.println(s3.equals(s4));//true
for(int i = 0; i < s3.length(); i++){
System.out.println(s3.charAt(i));
}
char[] arr = s3.toCharArray();//转字符数组
System.out.println(arr);
System.out.println(arr[0]);
String s6 = s3.substring(0,4);//abcd 截子串,索引区间前闭后开
System.out.println(s6);
System.out.println(s3.substring(1));//bcde 从目标索引开始直到末尾,截出子串
String s7 = s3.replace('b', '*');
System.out.println(s7);//a*cde
System.out.println(s7.contains("b"));//false 是否包含某个关键字(字符串形式)
System.out.println(s7.contains("cde"));//true
System.out.println(s7.contains("cdef"));//false 精准包含的判断
System.out.println(s7.startsWith("a*"));//true 是否以某个字符串开头
System.out.println(s7.startsWith("a*b"));//false
String s8 = "aa,bb,cc,dd";
String[] name = s8.split(",");//按指定字符串分割,并返回字符串数组
for (int i = 0; i < name.length; i++) {
System.out.println(name[i]);
}
有运算要放在堆里。
程序一在编译时,只知道s2是字符,运行时才知道其内容
程序二在编译时,知道字符串内容,可以进行转化,提高程序的执行性能
//String简单应用:用户登录,需满足账号和密码皆正确,最多尝试三次
public class User {
private String name;
private String password;
public User(){
}
public User(String name, String password){
this.name = name;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
import java.util.Scanner;
public class UserOperator {
public void login(User user){
int n = 3;
Scanner sc = new Scanner(System.in);
while (n-- != 0) {
String name = sc.next(), password = sc.next();
if(user.getName().equals(name) && user.getPassword().equals(password)){
System.out.println("successfully login~");
return ;
}
if(!user.getName().equals(name)) System.out.println("name error");
if(!user.getPassword().equals(password)) System.out.println("password error");
}
}
}
public class Login {
public static void main(String[] args) {
User user = new User("admin", "123456");
UserOperator uo = new UserOperator();
uo.login(user);
}
}
ArrayList list = new ArrayList();
list.add("aa");
list.add(1);
list.add(10.0);
list.add("中");
System.out.println(list);
System.out.println(list.size());
list.remove(1);
System.out.println(list);
list.add("aa");
list.add("bb");
list.remove("aa");//删除首次出现的指定元素
System.out.println(list);
list.set(0, "aa");
System.out.println(list);//修改指定索引处的内容
public class Account {
private String name;
private char gender;
private String id;
private String password;
private double limit;
public String getName() {
return name + (gender == '女' ? "女士" : "先生");
}
public void setName(String name) {
this.name = name;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public double getLimit() {
return limit;
}
public void setLimit(double limit) {
this.limit = limit;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
private double money;
}
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class ATM {
private ArrayList<Account> list = new ArrayList<>();
private Scanner sc = new Scanner(System.in);
private Random r = new Random();
private Account loginAcc;
public void start() {
System.out.println("=====ATM系统首页=====");
while (true) {
System.out.println("welcome to the system~");
System.out.println("select your operation:\n1.login\n2.create new account\nplease input number:");
int command = sc.nextInt();
switch (command) {
case 1:
login();
break;
case 2:
createAccount();
break;
default:
System.out.println("please input number 1 or 2!");
}
}
}
/**登录功能*/
private void login(){
System.out.println("===login===");
if(list.size() == 0){
System.out.println("当前无账户,请先注册!");
return;
}
while (true) {
System.out.println("please input your cardId:");
String id = sc.next();
Account acc = searchId(id);
if(acc == null)
System.out.println("the account is not exist,please inspect and input again!");
else{
System.out.println("welcome," + acc.getName());
loginAcc = acc;
break;
}
}
while(true){
System.out.println("please input password:");
String password = sc.next();
if(password.equals(loginAcc.getPassword())){
System.out.println("login successfully~");
break;
}
else{
System.out.println("your password is error!");
}
}
while (true) {
System.out.println("==selsect your operation==");
System.out.println("1.查询账户");
System.out.println("2.存款");
System.out.println("3.取款\n4.转账\n5.密码修改\n6.退出\n7.注销当前账户");
int command = sc.nextInt();
switch (command){
case 1:
showAccountInfo();
break;
case 2:
addMoney();
break;
case 3:
getMoney();
break;
case 4:
transfer();
break;
case 5:
modifyPassword();
return;
case 6:
System.out.println(loginAcc.getName() + "您已成功退出");
return;
case 7:
if(deleteAccount()){
return;
}
break;
default:
System.out.println("please input the number 1-7!");
}
}
}
/** 展示当前账号信息*/
private void showAccountInfo() {
System.out.println(loginAcc.getName() + ", your details are those:");
System.out.println("卡号:" + loginAcc.getId());
System.out.println("户主:" + loginAcc.getName());
System.out.println("性别:" + loginAcc.getGender());
System.out.println("密码:" + loginAcc.getPassword());
System.out.println("余额:" + loginAcc.getMoney());
System.out.println("单次限额:" + loginAcc.getLimit());
}
/**存款*/
private void addMoney(){
System.out.println("==存款==\n请输入存款金额:");
while (true) {
double money = sc.nextDouble();
if(money >= 0){
loginAcc.setMoney(loginAcc.getMoney() + money);
System.out.println("您已成功存款" + money + "元,当前账户余额" + loginAcc.getMoney());
break;
}
else{
System.out.println("存款数额请大于等于0哦!");
}
}
}
/**取款*/
private void getMoney(){
System.out.println("==取款==\n请输入取款金额:");
while (true) {
double money = sc.nextDouble();
if(money > loginAcc.getLimit()){
System.out.println("单次限额" + loginAcc.getLimit() + ",请重新输入取款金额!");
}
else if(money > loginAcc.getMoney()){
System.out.println("您的账户余额为" + loginAcc.getMoney() + ",已不足请重新输入取款金额!");
}
else{
loginAcc.setMoney(loginAcc.getMoney() - money);
System.out.println("您已成功取款" + money + "元,当前账户余额为" + loginAcc.getMoney());
break;
}
}
}
/**转账*/
private void transfer(){
System.out.println("==转账==");
if(list.size() < 2){
System.out.println("账户过少,请先创建充足用户再使用转账功能!");
return;
}
System.out.println("请输入待转账账号:");
String id = sc.next();
Account acc = searchId(id);
if(acc == null){
System.out.println("您输入的账号有误!");
}
else{
String name = "*" + acc.getName().substring(1);
System.out.println("请输入用户【" + name + "】姓氏进行验证:");
String family = sc.next();
if(family.charAt(0) == acc.getName().charAt(0)){
System.out.println("验证成功~");
if(loginAcc.getMoney() == 0){
System.out.println("账户余额不足!");
}
else{
System.out.println("请输入转账金额:");
double money = sc.nextDouble();
if(money > loginAcc.getMoney()){
System.out.println("账户余额不足!");
}
else{
acc.setMoney(acc.getMoney() + money);
loginAcc.setMoney(loginAcc.getMoney() - money);
System.out.println("成功转账" + money + "元,账号余额为" + loginAcc.getMoney());
}
}
}
else{
System.out.println("验证失败!");
}
}
}
/**密码修改*/
private void modifyPassword(){
System.out.println("==修改密码==");
while (true) {
System.out.println("请输入原密码:");
String password = sc.next();
if(password.equals(loginAcc.getPassword())){
while(true){
System.out.println("请输入新密码:");
String newPassword = sc.next();
System.out.println("请再次输入新密码:");
String verify = sc.next();
if(newPassword.equals(verify)){
loginAcc.setPassword(newPassword);
System.out.println("您已成功修改密码为" + loginAcc.getPassword());
return;
}
else{
System.out.println("两次输入密码不一致,请重新设置!");
}
}
}
else{
System.out.println("密码错误,请重新输入!");
}
}
}
/**销户*/
private boolean deleteAccount(){
if(loginAcc.getMoney() > 0){
System.out.println("当前还有未用余额,请先使用完毕再销户!");
return false;
}
else{
System.out.println(loginAcc.getName() + ",您已成功销户~");
list.remove(loginAcc);
return true;
}
}
private void createAccount() {
System.out.println("===create account===");
Account acc = new Account();
System.out.println("input name:");
acc.setName(sc.next());
System.out.println("input gender:");
while (true) {
char gender = sc.next().charAt(0);
if (gender == '男' || gender == '女') {
acc.setGender(gender);
break;
} else {
System.out.println("please input 男 or 女!");
}
}
while (true) {
System.out.println("input password:");
String password = sc.next();
System.out.println("verify your password:");
String password1 = sc.next();
if (password.equals(password1)) {
acc.setPassword(password);
break;
} else {
System.out.println("the two input password are different,please input again!");
}
}
System.out.println("input limit");
acc.setLimit(sc.nextDouble());
String id = createCardId();
acc.setId(id);
list.add(acc);
System.out.println("your card id is " + id + " and you can start use~");
}
private String createCardId() {
while (true) {
String id = "";
for (int i = 0; i < 8; i++) {
int num = r.nextInt(10);
id += num;
}
if (searchId(id) == null) {
return id;
}
}
}
private Account searchId(String id) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getId().equals(id)) return list.get(i);
}
return null;
}
}
public class Menu {
public static void main(String[] args) {
ATM atm = new ATM();
atm.start();
}
}
package singleInstance;
//饿汉式单例
public class SingleInstance {
//定义一个类变量记住类的一个对象
private static SingleInstance si = new SingleInstance();
//必须私有类的构造器
private SingleInstance(){
}
//定义一个方法返回类的对象
public static SingleInstance getObject(){
return si;
}
}
package singleInstance;
public class Test {
public static void main(String[] args){
SingleInstance si1 = SingleInstance.getObject();
SingleInstance si2 = SingleInstance.getObject();
System.out.println(si1);//@3b07d329
System.out.println(si2);//@3b07d329
}
}
package singleInstance;
public class LazySingleInstance {
//定义一个类变量,用于存储这个类的一个对象
private static LazySingleInstance l;
//类的构造器私有
private LazySingleInstance(){
}
//该类方法要保证当且仅当第一次调用时才创建一个对象,后续都用该对象返回
public static LazySingleInstance getObject(){
if(l == null){
l = new LazySingleInstance();
System.out.println("create object~");
}
return l;
}
}
package singleInstance;
public class Test {
public static void main(String[] args){
LazySingleInstance l1 = LazySingleInstance.getObject();
LazySingleInstance l2 = LazySingleInstance.getObject();
System.out.println(l1 == l2);//true
}
}
单继承
子类访问其他成员
super
关键字,指定访问父类的成员:super.父类成员变量/父类成员方法
//子类Student中的方法,其父类为Human
public void printName(){
String name = "method name";
System.out.println(name);//method name
System.out.println(this.name);//student.name 子类对象成员变量
System.out.println(super.name);//human name距离最近的父类的成员变量
}
package heyExtends;
public class Student {
private String name;
private int age;
private String spirit;
public String getSpirit() {
return spirit;
}
public void setSpirit(String spirit) {
this.spirit = spirit;
}
public Student() {
}
public Student(String name, int age){
this(name, age, "mortal");
}
public Student(String name, int age, String spirit) {
this.name = name;
this.age = age;
this.spirit = spirit;
}
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;
}
}
package heyExtends;
public class Test {
public static void main(String[] args){
Student s = new Student("Anna", 26);
System.out.println(s.getName());
System.out.println(s.getAge());
System.out.println(s.getSpirit());
}
}
package heyExtends;
public class Human {
public void run(){
System.out.println("human can run");
}
}
package heyExtends;
public class Student extends Human{
@Override
public void run(){
System.out.println("student runs fastly");
}
}
package heyExtends;
public class Teacher extends Human{
@Override
public void run(){
System.out.println("teacher hard to run");
}
}
package heyExtends;
public class Test {
public static void main(String[] args){
Human h = new Human();
Human h1 = new Student();
Human h2 = new Teacher();
h.run();//human can run
h1.run();//student runs fastly
h2.run();//teacher hard to run
}
}
常量:使用static final
修饰的成员变量。常量名建议用大写字母,中间用下划线隔开
父类知道每个子类都会做某个行为,但每个子类要做的情况细节不同,父类就定义为抽象方法,交给子类自己去重写实现,如此也是为了更好地支持多态。例如,每个动物都要干饭,但是蛇是整吞,人是咀嚼后再下咽方式是不同的。我们提前为动物类的干饭方法进行实现没有价值,定义为抽象方法(只有声明没有方法体)交给具体的子类实现才符合需求。
package helloInterface;
public interface Base {
String NAME = "Anna";
void eat();
private void sleep(){}
}
package helloInterface;
public interface Hard {
void study();
}
package helloInterface;
public abstract class Human implements Base, Hard{
// 实现全部接口的所有抽象方法,或者将实现类定义为抽象类
// @Override
// public void eat() {
//
// }
//
// @Override
// public void study() {
//
// }
}
package interfaceDemo;
public class Test {
public static void main(String[] args){
Manager m = new Manager();
m.printInfo();
m.printScore();
}
}
package interfaceDemo;
public class Student {
private String name;
private double score;
private char gender;
public Student() {
}
public Student(String name, double score, char gender) {
this.name = name;
this.score = score;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
}
package interfaceDemo;
import java.util.ArrayList;
public class Manager {
private ArrayList<Student> students = new ArrayList<>();
private StudentOperator so = new StudentOperatorImpl1();
public Manager(){
students.add(new Student("刘亦菲", 100, '女'));
students.add(new Student("古天乐", 90, '男'));
students.add(new Student("斯嘉丽", 150, '女'));
}
public void printInfo(){
so.printInfo(students);
}
public void printScore(){
so.printScore(students);
}
}
package interfaceDemo;
import java.util.ArrayList;
public interface StudentOperator {
void printInfo(ArrayList<Student> students);
void printScore(ArrayList<Student> students);
}
package interfaceDemo;
import java.util.ArrayList;
public class StudentOperatorImpl1 implements StudentOperator{
@Override
public void printInfo(ArrayList<Student> students) {
for(int i = 0; i < students.size(); i++){
Student s = students.get(i);
System.out.println("姓名:" + s.getName() + ",性别:" + s.getGender() + ",成绩:" + s.getScore());
}
}
@Override
public void printScore(ArrayList<Student> students) {
double sum = 0;
for (int i = 0; i < students.size(); i++) {
Student s = students.get(i);
sum += s.getScore();
}
System.out.println("平均分为:" + sum / students.size());
}
}
package interfaceDemo;
import java.util.ArrayList;
public class StudentOperatorImpl2 implements StudentOperator{
@Override
public void printInfo(ArrayList<Student> students) {
int boy = 0;
for(int i = 0; i < students.size(); i++){
Student s = students.get(i);
System.out.println("姓名:" + s.getName() + ",性别:" + s.getGender() + ",成绩:" + s.getScore());
if(s.getGender() == '男') boy++;
}
System.out.println("女生共有" + (students.size() - boy) + "人, 男生共有" + boy + "人");
}
@Override
public void printScore(ArrayList<Student> students) {
double sum = 0, max = students.get(0).getScore(), min = students.get(0).getScore();
for (int i = 0; i < students.size(); i++) {
Student s = students.get(i);
sum += s.getScore();
if(s.getScore() > max) max = s.getScore();
if(s.getScore() < min) min = s.getScore();
}
System.out.println("平均分为:" + (sum - max - min) / (students.size() - 2));
}
}
package interface_jdk8;
public interface Driver {
/**默认方法:
* 必须用default修饰,默认用public修饰
* 属于实例方法,必须用实现类的对象来访问
* */
default void driver(){
examDrive();
System.out.println("I can drive");
}
/**私有方法:必须使用private修饰
* 属于实例方法
* */
private void examDrive(){
System.out.println("got lisence!");
}
/**静态方法:必须使用static修饰,默认会被public修饰
* */
static void func(){
System.out.println("static method did");
}
void func1();
}
package interface_jdk8;
public class Human implements Driver{
@Override
public void func1(){
}
}
package interface_jdk8;
public class Test {
public static void main(String[] args){
Human h = new Human();
h.driver();
//h.examDrive();报错
//Human.func();报错
Driver.func();
}
}
package multiInterface;
public class hello {
}
interface A{
void funcA();
}
interface B{
void funcB();
}
//接口是多继承的
interface C extends A, B{
}
class D implements C{
@Override
public void funcA() {
}
@Override
public void funcB() {
}
}
package multiInterface;
public class Hey {
public static void main(String[] args){
DD d = new DD();
d.test();//test did
H h = new H();
h.test();//I am method in your super(father)
}
}
interface AA{
void test();
//void test1();报错
}
interface BB{
void test();
//String test1();一个接口继承多个接口时,若多个接口中存在方法签名冲突,则不支持多继承
}
interface CC extends AA, BB{
}
class DD implements CC{
@Override
public void test() {
System.out.println("test did");
}
}
//报错。当一个类实现多个接口时,若多个接口中存在方法签名冲突,则不支持多实现
//class E implements AA, BB{
//
//}
class F{
public void test(){
System.out.println("I am method in your super(father)");
}
}
interface G{
default void test(){
System.out.println("I am method in your interface");
}
}
//当一个类同时继承了父类且实现了接口,且父类和接口中有同名的默认方法,实现类会优先使用父类中
class H extends F implements G{
}
interface J{
default void test(){
System.out.println("J method");
}
}
interface K{
default void test(){
System.out.println("K method");
}
}
//一个类中实现了多个接口,多个接口中存在多个同名的方法,可以不冲突,需要在这个类中重写该方法即可
class L implements J, K{
public void test(){
System.out.println("L method, myself");
}
}
package helloInner;
public class Outer {
private int age = 1;
public static String school;
public class Inner{
private int age = 2;
void test(){
System.out.println(school);
int age = 3;
System.out.println(age);//3
System.out.println(this.age);//2
System.out.println(Outer.this.age);//1
}
}
}
package helloInner;
public class Test {
public static void main(String[] args) {
Outer.Inner inner = new Outer().new Inner();
inner.test();
}
}
package helloInner;
public class Outer {
private int age = 1;
public static String school;
public static class Inner{
private int age = 2;
void test(){
System.out.println(school);
int age = 3;
System.out.println(age);//3
System.out.println(this.age);//2
//System.out.println(Outer.this.age);报错
}
}
public static void test(){
//System.out.println(age);报错,在静态方法里不能直接访问实例变量,实例变量是属于每个对象的
System.out.println(school);
}
public void test1(){
System.out.println(age);
System.out.println(school);
}
}
package helloInner;
public class Test {
public static void main(String[] args) {
Outer.Inner inner = new Outer.Inner();
inner.test();
}
}
package helloInner;
public class Hello {
public static void main(String[] args){
Animal animal = new Animal(){
@Override
void cry(){
System.out.println("I can cry by miao");
}
};
animal.cry();//I can cry by miao
}
}
class Animal{
void cry(){
System.out.println("I can cry");
}
}
package helloInner;
public class Human {
public static void main(String[] args){
Driver driver = new Driver(){
@Override
public void driver(){
System.out.println("driving");
}
};
complete(driver);//the complete starts \n driving
}
public static void complete(Driver driver){
System.out.println("the complete starts");
driver.driver();
}
}
package helloInner;
public interface Driver {
void driver();
}
package helloEnum;
public enum Student {
Wang, Liu, Gu;
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
package helloEnum;
public class Test {
public static void main(String[] args){
//Student s = new Student();枚举类的构造器都是私有的,不能对外创建对象
Student student = Student.Wang;//枚举类的第一行都是常量,它们是枚举类的对象
System.out.println(student);//Wang
System.out.println(student.getId());//null
Student[] students = Student.values();//拿到全部对象
Student student1 = Student.valueOf("Liu");
System.out.println(student1.name());//Liu
System.out.println(student1.ordinal());//1 索引
for(int i = 0; i < students.length; i++){
System.out.println(students[i].name());
}
}
}
匿名内部类
package abstractEnum;
public enum Student {
Wang("WANG"){
@Override
public void study(){
System.out.println(getName() + " is studying");
}
}, Liu(){
@Override
public void study(){
System.out.println(getName() + " is studying");
}
};
private String name;
Student() {
}
Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public abstract void study();
}
package abstractEnum;
public class Test {
public static void main(String[] args){
Student s = Student.Wang;
s.study();//WANG is studying
}
}
package applyEnum;
public enum Constant {
YES, NO;
}
package applyEnum;
public class Seclect {
public static void main(String[] args){
select(Constant.YES);//passed successfully
}
public static void select(Constant constant){
switch (constant){
case YES :
System.out.println("passed successfully");
break;
case NO:
System.out.println("sorry, not pass!");
break;
default:
System.out.println("try again");
}
}
}
package helloObject;
import java.util.Objects;
//Cloneable是一种标记接口(标记接口里面没有内容)
//标记接口可理解为一种规则
public class Student implements Cloneable{
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
//若两个对象地址一样,则直接返回true
if (this == o) return true;
//若o为null或者两者类型不一样,直接返回false
if (o == null || getClass() != o.getClass()) return false;
//类型相同,则分别比较其成员内容
Student student = (Student) o;
return age == student.age && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
//对象克隆
@Override
protected Object clone() throws CloneNotSupportedException {
//super去调用Object父类中的clone()方法
return super.clone();
}
}
package helloObject;
public class Test {
public static void main(String[] args) throws CloneNotSupportedException {
Student student = new Student("伍佰", 55);
Student student1 = new Student("伍佰", 55);
System.out.println(student);//Student{name='伍佰', age=55}
System.out.println(student.equals(student1));//true
Student student2 = (Student) student.clone();
System.out.println(student2);//Student{name='伍佰', age=55}
}
}
package helloObjects;
import java.util.Objects;
public class Test {
public static void main(String[] args){
String s = null, s1 = "Stay Hungry", s2 = "Stay Hungry";
System.out.println(s1.equals(s2));//true
System.out.println(Objects.equals(s1, s2));//true 后者这种比较方式更安全,能够处理一方为null的情况
//System.out.println(s.equals(s1));报错Cannot invoke "String.equals(Object)" because "s" is null
System.out.println(Objects.equals(s, s1));//false
System.out.println(Objects.isNull(s));//true
System.out.println(s == null);//true 这两种判断方法等价,更推荐第二种因为更方便
System.out.println(Objects.nonNull(s));//false
System.out.println(Objects.nonNull(s1));//true
}
}
Java中的核心思想是万物皆对象,但是八种基本类型并不是对象
package helloInteger;
import java.util.ArrayList;
public class Test {
public static void main(String[] args){
//Integer i1 = new Integer(101);已过时
Integer i2 = Integer.valueOf(101);
System.out.println(i2);//101
//自动装箱:可以自动地把基本数据转换为对象
Integer i3 = 102;
//自动拆箱:可以自动把包装类型的对象转换为对应的基本数据类型
Integer i4 = i3;
//泛型和集合不支持基本数据类型,只能支持引用数据类型
//ArrayList list = new ArrayList();报错,不能是基本数据类型
ArrayList<Integer> list = new ArrayList<>();
list.add(101);//自动装箱
list.add(102);//自动装箱
int n = list.get(0);//自动拆箱
System.out.println(n);//101
//把基本数据类型转换为字符串
Integer i5 = 105;
String s = Integer.toString(i5);
System.out.println(s + 1);//1051
String s1 = i5.toString();
System.out.println(s1 + 1);//1051
String s2 = i5 + "";//推荐该种转换为字符串的方式
System.out.println(s2 + 1);//1051
//字符串类型转化为对应的基本数据类型
String s3 = "101";//101.5报错
int i = Integer.parseInt(s3);
int i1 = Integer.valueOf(s3);//更推荐该种方式
System.out.println(i + 1);//102
System.out.println(i1 + 1);//102
String s4 = "100";//100或者100.0都可以
double d = Double.parseDouble(s4);
double d1 = Double.valueOf(s4);//推荐该种转换方式
System.out.println(d + 0.5);//100.5
System.out.println(d1 + 0.5);//100.5
}
}
package helloStringBuilder;
public class Test {
public static void main(String[] args){
StringBuilder s = new StringBuilder("a");
s.append("b");
s.append(6);
s.append("中文");
//支持链式编程 append()返回的是增加完之后的StringBuilder,而其本身又是能继续添加的
s.append("c").append("d").append("e");
System.out.println(s);//ab6中文cde
System.out.println(s.reverse());//edc文中6ba
System.out.println(s.length());//8
String string = s.toString();
System.out.println(string);//edc文中6ba
}
}
package helloStringBuilder;
public class Hello {
public static void main(String[] args){
// String s = "";等待时间过久,并异常结束
// int max = 1000000;
// for(int i = 0; i < max; i++)
// s += "abc";
// System.out.println(s);
int max = 1000000;
StringBuilder sb = new StringBuilder();
for(int i = 0; i < max; i++){
sb.append("abc");
}
System.out.println(sb);//能够正确输出
}
}
package helloStringJoiner;
import java.util.StringJoiner;
public class Test {
public static void main(String[] args){
StringJoiner sj1 = new StringJoiner(",");
StringJoiner sj2 = new StringJoiner(",", "[", "]");
sj1.add("刘亦菲");
sj1.add("Scarlett");
System.out.println(sj1);//刘亦菲,Scarlett
System.out.println(sj1.length());//12 返回字符出现的次数
sj2.add("古天乐");
sj2.add("Jaskon");
System.out.println(sj2);//[古天乐,Jaskon]
}
}
package helloMath;
public class Test {
public static void main(String[] args){
//abs()取绝对值
System.out.println(Math.abs(0));//0
System.out.println(Math.abs(0.0));//0.0
System.out.println(Math.abs(-3.19));//3.19
//ceil()向上取整
System.out.println(Math.ceil(6.0000001));//7.0
System.out.println(Math.ceil(4));//4.0
System.out.println(Math.ceil(-4.1));//-4.0
System.out.println(Math.ceil(-0.9));//-0.0
//floor()向下取整
System.out.println(Math.floor(6.99999999));//6.0
System.out.println(Math.floor(-0.001));//-1.0
//round()四舍五入
System.out.println(Math.round(4.45));//4
System.out.println(Math.round(-4.45));//-4
System.out.println(Math.round(4.44444444445));//4
System.out.println(Math.round(-4.44444444445));//-4
System.out.println(Math.round(4.54));//5
System.out.println(Math.round(-4.54));//-5
//max()取最大值 min()取最小值
System.out.println(Math.max(1, 2));//2
System.out.println(Math.min(-3.0, -1.0));//-3.0
//pow(a, b) a^b
System.out.println(Math.pow(-2, 3));//-8.0
System.out.println(Math.pow(2, -1));//0.5
//random() [0.0, 1.0)之间的随机值
System.out.println(Math.random());//0.20535836387179296
}
}
package helloRuntime;
public class Test {
public static void main(String[] args) {
Runtime runtime = Runtime.getRuntime();//返回当前与Java应用程序关联的运行时对象
System.out.println(runtime.availableProcessors());//8 获取虚拟机能使用的虚拟机数
System.out.println(runtime.totalMemory() / 1024.0 / 1024.0 + "MB");//128.0MB 返回Java虚拟机中的内存总量
System.out.println(runtime.freeMemory() / 1024.0 / 1024.0 + "MB");//124.5379409790039MB 返回Java虚拟机中的可用内存量
}
}
package helloBigDecimal;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Test {
public static void main(String[] args){
//浮点数运算可能会出现结果失真
double a = 0.1, b = 0.2;//0.30000000000000004
System.out.println(a + b);
//把double变成字符串,封装为DigDecimal对象来运算
// BigDecimal a1 = new BigDecimal(Double.toString(a));
// BigDecimal b1 = new BigDecimal(Double.toString(b));
//推荐使用该方式,更简洁
BigDecimal a1 = BigDecimal.valueOf(a);
BigDecimal b1 = BigDecimal.valueOf(b);
BigDecimal c = BigDecimal.valueOf(0.3);
BigDecimal c1 = a1.add(b1);
System.out.println(c1);//0.3
BigDecimal c2 = a1.subtract(b1);
System.out.println(c2);//-0.1
BigDecimal c3 = a1.multiply(b1);
System.out.println(c3);//0.02
BigDecimal c4 = a1.divide(b1);
System.out.println(c4);//0.5
//BigDecimal c5 = a1.divide(c, 2, RoundingMode.HALF_UP);报错,结果1/3不是一个精确值,而BigDecimal需要给出一个精确值
BigDecimal c5 = a1.divide(c, 2, RoundingMode.HALF_UP);
System.out.println(c5);//0.33
}
}
package helloDate;
import java.util.Date;
public class Test {
public static void main(String[] args){
Date date = new Date();//系统当前时间
System.out.println(date);//Sun Oct 15 21:49:30 CST 2023
long time = date.getTime();//拿到时间毫秒值
Date date1 = new Date(time + 2 * 1000);//2s之后的时间是多少 把时间毫秒值转换为日期对象
System.out.println(date1);//Sun Oct 15 21:49:32 CST 2023
Date date2 = new Date();
date2.setTime(time + 2 * 1000);//直接把日期对象的时间通过setTime()修改
System.out.println(date2);//Sun Oct 15 21:49:32 CST 2023
}
}
package helloSimpleDateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
public static void main(String[] args){
Date date = new Date();
System.out.println(date);//Sun Oct 15 22:03:04 CST 2023
long time = date.getTime();
//格式化日期时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss EEE a");
String d = sdf.format(date);
System.out.println(d);//2023年10月15日 22:03:04 周日 下午
}
}
//解析字符串时间成为日期对象
String s = "2024-01-01 13:14:00";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//指定的时间格式需要与被解析的时间格式一致,否则会报错
Date date1 = sdf1.parse(s);
System.out.println(date1);//Mon Jan 01 13:14:00 CST 2024
简单案例:秒杀系统
package helloSimpleDateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SecondSystem {
public static void main(String[] args) throws ParseException {
String start = "2023年11月11日 00:00:00";
String end = "2023年11月11日 00:10:00";
String liu = "2023年11月11日 00:03:15";
String wang = "2023年11月11日 00:10:01";
//字符串时间解析为日期对象
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
Date startDate = sdf.parse(start);
Date endDate = sdf.parse(end);
Date liuDate = sdf.parse(liu);
Date wangDate = sdf.parse(wang);
//把日期对象转换为毫秒值方便比较
long startTime = startDate.getTime();
long endTime = endDate.getTime();
long liuTime = liuDate.getTime();
long wangTime = wangDate.getTime();
if(startTime <= liuTime && endTime >= liuTime){//liu下单成功
System.out.println("liu下单成功");
}
else{
System.out.println("liu下单失败");
}
if(startTime <= wangTime && endTime >= wangTime){//wang下单失败
System.out.println("wang下单成功");
}
else{
System.out.println("wang下单失败");
}
}
}
package helloCalender;
import java.util.Calendar;
import java.util.Date;
public class Test {
public static void main(String[] args) {
//获取系统此刻时间对应的日历对象
Calendar now= Calendar.getInstance();
System.out.println(now);
//获取日历中的某个信息
int day = now.get(Calendar.DAY_OF_YEAR);
System.out.println(day);//289
//获取日历中的日期对象
Date date = now.getTime();
System.out.println(date);//Mon Oct 16 09:45:39 CST 2023
//获取日历中的时间毫秒值
long time = now.getTimeInMillis();
System.out.println(time);
//修改日历中的某个信息
now.set(Calendar.DAY_OF_YEAR, 300);
System.out.println(now);
//对日历中的某个信息增加或减少
now.add(Calendar.DAY_OF_YEAR, 20);
now.add(Calendar.DAY_OF_YEAR, -10);
now.add(Calendar.HOUR, 5);
System.out.println(now);
}
}
* LocalDate
* LocalTime
* LocalDateTime(三者类似)
package helloLocalDate;
import java.time.LocalDate;
import java.util.Calendar;
public class Test {
public static void main(String[] args) {
//获取本地日期对象
LocalDate ld = LocalDate.now();//2023-10-16
System.out.println(ld);
//获取日期对象中的信息
int year = ld.getYear();
int month = ld.getMonthValue();
int day = ld.getDayOfMonth();
int days = ld.getDayOfYear();
int dayOfWeek = ld.getDayOfWeek().getValue();
System.out.println(day);//16
System.out.println(dayOfWeek);//1
//直接修改某个信息
LocalDate ld1 = ld.withYear(2107);
System.out.println(ld);//2023-10-16 不改变
System.out.println(ld1);//2107-10-16
//增加或减少某个信息
LocalDate ld2 = ld.plusWeeks(4);
LocalDate ld3 = ld.minusWeeks(1);
System.out.println(ld2);//2023-11-13
System.out.println(ld3);//2023-10-09
//获取指定日期的LocalDate对象
LocalDate ld4 = LocalDate.of(2024, 1, 1);
System.out.println(ld4);//2024-01-01
//判断两个日期是否相等,是在前还是在后
System.out.println(ld4.equals(ld3));//false
System.out.println(ld3.isAfter(ld4));//false
System.out.println(ld3.isBefore(ld4));//true
}
}
package helloZone;
import java.time.Clock;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Test {
public static void main(String[] args) {
//获取系统默认的时区
ZoneId zoneId = ZoneId.systemDefault();
System.out.println(zoneId);//Asia/Shanghai
System.out.println(zoneId.getId());//Asia/Shanghai
//获取Java支持的全部时区id
System.out.println(ZoneId.getAvailableZoneIds());//静态方法
//把某个时区id封装为ZoneId对象
ZoneId zoneId1 = ZoneId.of("Asia/Aqtau");
System.out.println(zoneId1);//Asia/Aqtau
//ZoneDateTime带时区的时间
//now(ZoneId zId)获取某个时区的ZonedDateTime对象
ZonedDateTime zDate = ZonedDateTime.now(zoneId1);
System.out.println(zDate);//2023-10-16T16:46:20.994661800+05:00[Asia/Aqtau]
//世界标准时间
ZonedDateTime zDate1 = ZonedDateTime.now(Clock.systemUTC());
System.out.println(zDate1);//2023-10-16T11:46:20.994661800Z
//获取系统默认时区时间
ZonedDateTime zDate2 = ZonedDateTime.now();
System.out.println(zDate2);//2023-10-16T19:46:20.878431400+08:00[Asia/Shanghai]
}
}
package helloInstant;
import java.time.Instant;
public class Test {
public static void main(String[] args) {
//获取此刻时间信息
Instant now = Instant.now();//不可变对象
System.out.println(now);//2023-10-16T11:56:59.381477500Z
//获取总秒数
long second = now.getEpochSecond();
System.out.println(second);//1697457419
//获取不足一秒的纳秒数
int nano = now.getNano();
System.out.println(nano);//381477500
}
}
package helloDateTimeFormatter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Test {
public static void main(String[] args) {
//创建日期时间格式化器对象
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
//对时间进行格式化
LocalDateTime now = LocalDateTime.now();
System.out.println(now);//2023-10-16T20:32:24.018059900
//方案一
String rs = formatter.format(now);
System.out.println(rs);//2023年10月16日 20:32:24
//方案二
String rs1 = now.format(formatter);
System.out.println(rs1);//2023年10月16日 20:32:24
//解析时间
String dateStr = "2023年10月16日 20:30:53";
LocalDateTime ldt = LocalDateTime.parse(dateStr, formatter);
System.out.println(ldt);//2023-10-16T20:30:53
}
}
package helloGap;
import java.time.LocalDate;
import java.time.Period;
public class TestPeriod {
public static void main(String[] args) {
LocalDate localDate1 = LocalDate.of(2024, 2, 5);
LocalDate localDate2 = LocalDate.of(2025, 1, 1);
Period period = Period.between(localDate1, localDate2);
System.out.println(period.getYears());//0
System.out.println(period.getMonths());//10
System.out.println(period.getDays());//27
}
}
package helloGap;
import java.time.Duration;
import java.time.LocalDateTime;
public class TestDuration {
public static void main(String[] args) {
LocalDateTime start = LocalDateTime.of(2024, 1, 1, 0, 0, 0);
LocalDateTime end = LocalDateTime.of(2024, 12, 31, 12, 59, 59);
Duration duration = Duration.between(start, end);
System.out.println(duration.toDays());//365
System.out.println(duration.toHours());//8772
System.out.println(duration.toMinutes());//526379
System.out.println(duration.getSeconds());//31582799
System.out.println(duration.getNano());//0
long time = duration.toNanos();
System.out.println(time);//31582799000000000
}
}
package helloLambda;
public class Test {
public static void main(String[] args){
Driver driver = new Driver() {
@Override
public void driver() {
System.out.println("I can drive");
}
};
driver.driver();//I can drive
Driver driver1 = () ->{ //(形参列表) -> {被重写方法的代码体}
System.out.println("driving~");
};
driver1.driver();//driving~
Read read = new Read() {
@Override
public void read() {
System.out.println("I can read");
}
};
read.read();//I can read
//Lambda表达式只能简化函数式接口的匿名内部类
// Read read1 = () -> {//报错 Target type of a lambda conversion must be an interface
// System.out.println("reading");
// };
}
}
interface Driver{
void driver();
}
abstract class Read{
public abstract void read();
}
package helloLambda;
public class Hello {
public static void main(String[] args){
Write write = time -> time + ", all writing";
write.write(8);
Study study = (time, task) -> System.out.println("studying " + time + " hour");
study.study(8, 10);//studying 8 hour
}
}
interface Write{
String write(int time);
}
interface Study{
void study(int time, int task);
}
package helloCite;
import java.util.Arrays;
import java.util.Comparator;
public class Test {
public static void main(String[] args){
Student[] students = new Student[3];
students[0] = new Student("Liu", 25, 100);
students[1] = new Student("Gu", 26, 101);
students[2] = new Student("Wang", 24, 102);
//原始写法,对学生数组按照年龄排序
// Arrays.sort(students, new Comparator() {
// @Override
// public int compare(Student o1, Student o2) {
// return o1.getAge() - o2.getAge();
// }
// });
//使用Lambda简化后的形式
//Arrays.sort(students, (o1, o2) -> o1.getAge() - o2.getAge());
//Arrays.sort(students, (o1, o2) -> CompareByData.compareByAge(o1, o2));
//静态方法引用
Arrays.sort(students, CompareByData::compareByAge);
System.out.println(Arrays.toString(students));
}
}
package helloCite;
public class Student {
private String name;
private int age;
private double score;
public Student() {
}
public Student(String name, int age, double score) {
this.name = name;
this.age = age;
this.score = score;
}
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 double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", score=" + score +
'}';
}
}
package helloCite;
public class CompareByData {
public static int compareByAge(Student o1, Student o2){
return o1.getAge() - o2.getAge();
}
}
package helloCite;
import java.util.Arrays;
import java.util.Comparator;
public class HelloReference {
public static void main(String[] args) {
String[] names = {"Liu", "li", "Anna", "a"};
System.out.println(Arrays.toString(names));//[Liu, li, Anna, a]
//忽略大小写进行首字母排序
//原始版本
// Arrays.sort(names, new Comparator() {
// @Override
// public int compare(String o1, String o2) {
// return o1.compareToIgnoreCase(o2);
// }
// });
//Lambda表达式
//Arrays.sort(names, ((o1, o2) -> o1.compareToIgnoreCase(o2)));
//特定类型引用
Arrays.sort(names, String::compareToIgnoreCase);
System.out.println(Arrays.toString(names));
}
}
package helloCite;
public class TestReference {
public static void main(String[] args) {
//创建接口匿名内部类的对象 原始版本
// GetStudent gs = new GetStudent() {
// @Override
// public Student get(String name, int age, double score) {
// return new Student(name, age, score);
// }
// };
//Lambda表达式
//GetStudent gs = (name, age, score) -> new Student(name, age, score);
//构造器引用
GetStudent gs = Student::new;
Student s = gs.get("Liu", 25, 100);
System.out.println(s);
}
}
interface GetStudent{
Student get(String name, int age, double score);
}
package helloRegex;
public class Check {
public static void main(String[] args) {
String id1 = "01234", id2 = "a67899", id3 = "123456";
System.out.println(checkId(id1));//false
System.out.println(checkId(id2));//false
System.out.println(checkId(id3));//true
System.out.println(checkId1(id1));//false
System.out.println(checkId1(id2));//false
System.out.println(checkId1(id3));//true
}
//qq号需要满足:长度在6-20之间;全由数字组成;首位数字不能为0
public static boolean checkId(String id){
if(id == null || id.length() > 20 || id.length() < 5 || id.charAt(0) == '0') return false;
for(int i = 0; i < id.length(); i++){
char c = id.charAt(i);
if(c < '0' || c > '9') return false;
}
return true;
}
public static boolean checkId1(String id){
return id != null && id.matches("[1,9]\\d{5,19}");
}
}
package helloRegex;
import java.util.Scanner;
public class Check1 {
private static Scanner sc = new Scanner(System.in);
public static void main(String[] args){
getNum();
getEmail();
getTime();
}
/**电话号码可能有手机号和座机号两种
* 手机号要求:首位为1;第二位不能为0—2;长度为11位
* 座机号要求:区号首位为0;区号长度为3-8;区号和号码中间可选用‘-’分隔,有无皆可;号码首位非0;号码长度5-20
* */
public static void getNum(){
while(true){
System.out.println("请键入您的号码:");
String num = sc.nextLine();
if(num.matches("(1[3-9]\\d{9})|(0\\d{2,7}-?[1-9]\\d{4,19})")){
System.out.println("您已输入有效号码~");
break;
}
else{
System.out.println("您输入的号码格式有误!");
}
}
}
/**邮箱格式要求:@前为长度大于等于2的字母或数字;中间用‘@’分隔;公司名长度2-20之间;公司名整体可以出现一到两次
* */
public static void getEmail(){
while(true){
System.out.println("请键入您的邮箱:");
String email = sc.nextLine();
if(email.matches("\\w{2,}@\\w{2,20}(\\.\\w{2,20}){1,2}")){
System.out.println("您已输入有效邮箱~");
break;
}
else{
System.out.println("您输入的邮箱格式有误!");
}
}
}
/**时间要求:小时在0-23之间;分钟和秒数在0-59之间
* */
public static void getTime(){
while(true){
System.out.println("请输入您的注册时间:");
String time = sc.nextLine();
if(time.matches("(([0-1]?[0-9])|(2[0-3])):([0-5]?[0-9])::([0-5]?[0-9])")){
System.out.println("您已输入有效时间");
break;
}
else
System.out.println("您输入的时间格式有误");
}
}
}
package helloRegex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FindInfo {
public static void main(String[] args){
//从给定信息中查找出手机号,邮箱,座机,热线电话(以400开头)
String data = "welocme to the system!\n" +
"about us: telephone: 19123456789, 17098765432" +
"and email: [email protected]" +
" the landline number:011-554032" +
"hot wire telephone:400-123456, 4009876543";
//定义爬取规则
String regex = "((1[3-9]\\d{9})|(0\\d{2,7}-?[1-9]\\d{4,19}))|(\\w{2,}@\\w{2,20}(\\.\\w{2,20}){1,2})"
+ "|(400-?\\d{3,7}-?\\d{3,7})";
//把正则表达式封装为一个Pattern对象
Pattern pattern = Pattern.compile(regex);
//通过Pattern对象去获取查找内容的匹配器对象
Matcher matcher = pattern.matcher(data);
while(matcher.find()){
System.out.println(matcher.group());
/**19123456789
17098765432
[email protected]
011-554032
400-123456
4009876543
* */
}
}
}
package helloRegex;
import java.util.Arrays;
public class Replace {
public static void main(String[] args){
//replcaceAll()把正则表达式所匹配的内容进行替换
String data1 = "刘亦菲fjdk45f古天乐jfdkla0吴彦祖";
System.out.println(data1.replaceAll("\\w+", "-"));//刘亦菲-古天乐-吴彦祖
//去重
//(.) 一组,匹配任意字符
//\\1 为这个组声明一个组号,1号
//+ 声明必须是重复出现的
//$1 取到一份第1组所重复的内容
String data2 = "保保保保保持饥饥饥饥饥饿饿饿饿饿饿";
System.out.println(data2.replaceAll("(.)\\1+", "$1"));//保持饥饿
//用正则表达式所匹配的内容对字符串进行分割,返回处理后的字符串
String[] names = data1.split("\\w+");
System.out.println(Arrays.toString(names));//[刘亦菲, 古天乐, 吴彦祖]
}
}
异常的划分
package helloException;
import java.util.Scanner;
public class Test {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
try {
saveAge(sc.nextInt());
System.out.println("successfully saved");
} catch (Exception e) {
e.printStackTrace();
System.out.println("error in basis");
}
}
public static void saveAge(int age){
if(age >= 0 && age <= 500) System.out.println("your age successfully saved");
else throw new AgeIllegalException("/age is illegal ! your age is " + age);
}
}
package helloException;
public class AgeIllegalException extends RuntimeException{
public AgeIllegalException() {
}
public AgeIllegalException(String message) {
super(message);
}
}
package helloException;
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
while(true){
try {
getScore();
break;
} catch (Exception e) {
System.out.println("please legally input");
}
}
}
public static void getScore(){
Scanner sc = new Scanner(System.in);
double score = sc.nextDouble();
while (true) {
if(score < 0){
System.out.println("your input is illegal,please input again");
}
else{
System.out.println("successful input");
break;
}
}
}
}
package helloCollection;
import java.util.ArrayList;
import java.util.HashSet;
public class Test {
public static void main(String[] args){
//list:有序、可重复、有索引
ArrayList<String> list = new ArrayList<>();
list.add("java2");
list.add("java1");
list.add("java1");
list.add("java3");
System.out.println(list);//[java2, java1, java1, java3]
System.out.println(list.get(2));
//HashSet:无序、不重复、无索引
HashSet<String> set = new HashSet<>();
set.add("java2");
set.add("java1");
set.add("java1");
set.add("java3");
System.out.println(set);//[java3, java2, java1]
//System.out.println(set.get(2));报错Cannot resolve method 'get' in 'HashSet'
}
}
package helloCollection;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class CollectionMethod {
public static void main(String[] args) {
Collection<String> collection = new ArrayList<>();//多态
//boolean add(E e)添加成功返回true
collection.add("java2");
collection.add("java1");
collection.add("java1");
collection.add("java3");
System.out.println(collection);//[java2, java1, java1, java3]
//void clear()清空集合元素
collection.clear();
System.out.println(collection);//[]
//boolean isEmpty()集合为空 则返回true
System.out.println(collection.isEmpty());//true
//int size()获取集合的大小
System.out.println(collection.size());//0
collection.add("java2");
collection.add("java1");
collection.add("java1");
collection.add("java3");
System.out.println(collection.size());//4
//boolean contains(Object o)判断集合中是否包含某个元素,若有则返回true
System.out.println(collection.contains("java1"));//true
System.out.println(collection.contains("Java1"));//false 精确匹配
//boolean remove(E e)删除某个元素,删除成功返回true;若有多个重复元素,默认删除最先出现的
System.out.println(collection.remove("java1"));//true
System.out.println(collection.remove("java4"));//false
System.out.println(collection);//[java2, java1, java3]
//Object[] toArray()把集合转换为数组
Object[] arr = collection.toArray();
System.out.println(Arrays.toString(arr));//[java2, java1, java3]
//需要确保集合中的数据类型全为字符串!
String[] arr1 = collection.toArray(new String[collection.size()]);
System.out.println(Arrays.toString(arr1));//[java2, java1, java3]
//c1.addAll(c2)使用条件:需要满足集合c1,c2中的数据类型相同;功能:把c2的全部元素加到c1中
Collection<String> collection1 = new ArrayList<>();
collection1.add("java5");
collection1.add("java6");
collection.addAll(collection1);
System.out.println(collection);//[java2, java1, java3, java5, java6]
}
}
package helloIterator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Test {
public static void main(String[] args){
Collection<String> c = new ArrayList<>();
c.add("java3");
c.add("java1");
c.add("java1");
c.add("java2");
System.out.println(c);//[java3, java1, java1, java2]
//使用迭代器遍历集合
//①从集合对象中获取迭代器对象
Iterator<String> iterator = c.iterator();
System.out.println(iterator.next());//java3
System.out.println(iterator.next());//java1
//循环结合迭代器遍历集合
while(iterator.hasNext()){//判取一一对应,换言之问一次取一次
System.out.println(iterator.next());
}
}
}
package enhanceFor;
import java.util.ArrayList;
import java.util.Collection;
public class Test {
public static void main(String[] args){
Collection<String> c = new ArrayList<>();
c.add("java3");
c.add("java1");
c.add("java2");
for(String ele : c){
System.out.println(ele);
}
String[] names = {"Anna", "Jerry", "Tom"};
for(String ele : names){
System.out.println(ele);
}
}
}
package helloLambda1;
import java.util.ArrayList;
import java.util.Collection;
import java.util.function.Consumer;
public class Test {
public static void main(String[] args) {
Collection<String> c = new ArrayList<>();
c.add("java3");
c.add("java1");
c.add("java1");
c.add("java2");
System.out.println(c);//[java3, java1, java1, java2]
//结合Lambda表达式遍历集合
// c.forEach(new Consumer() {
// @Override
// public void accept(String s) {
// System.out.println(s);
// }
// });
//简化版本1
// c.forEach((String s) -> {
// System.out.println(s);
// });
//简化版本2
// c.forEach(s -> System.out.println(s));
//简化版本3
c.forEach(System.out::println);
}
}
package helloCollection;
public class Movie {
private String name;
private double score;
private String actor;
public Movie() {
}
public Movie(String name, double score, String actor) {
this.name = name;
this.score = score;
this.actor = actor;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public String getActor() {
return actor;
}
public void setActor(String actor) {
this.actor = actor;
}
@Override
public String toString() {
return "Movie{" +
"name='" + name + '\'' +
", score=" + score +
", actor='" + actor + '\'' +
'}';
}
}
package helloCollection;
import java.util.ArrayList;
import java.util.Collection;
public class Index {
public static void main(String[] args) {
Collection<Movie> c = new ArrayList<>();
c.add(new Movie("窈窕淑女", 9.9, "赫本"));
c.add(new Movie("乱世佳人", 10.0, "费雯丽"));
c.add(new Movie("大独裁者", 10.0, "卓别林"));
System.out.println(c);
for(Movie m : c){
System.out.println(m);
}
}
}
package helloList;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
//ArrayList:有序、可重复、有索引
List<String> list = new ArrayList<>();
list.add("斯嘉丽");
list.add("艾希礼");
list.add("梅兰妮");
list.add("弗兰克");
System.out.println(list);//[斯嘉丽, 艾希礼, 梅兰妮, 弗兰克]
//void add(int index, Element e)在指定位置插入元素
list.add(1, "瑞得");
System.out.println(list);//[斯嘉丽, 瑞得, 艾希礼, 梅兰妮, 弗兰克]
//E remove(int index)删除指定位置的元素,并返回被删除元素
System.out.println(list.remove(4));//弗兰克
System.out.println(list);//[斯嘉丽, 瑞得, 艾希礼, 梅兰妮]
//E set(int index, Element e)修改指定位置的元素,并返回被修改的元素
System.out.println(list.set(2, "阿亮"));//艾希礼
System.out.println(list);//[斯嘉丽, 瑞得, 阿亮, 梅兰妮]
//E get(int index)返回指定索引处的元素
System.out.println(list.get(3));//梅兰妮
}
}
package helloList;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Test1 {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("斯嘉丽");
list.add("艾希礼");
list.add("梅兰妮");
list.add("弗兰克");
System.out.println(list);//[斯嘉丽, 艾希礼, 梅兰妮, 弗兰克]
//1.for循环(因为有索引)
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
System.out.println("-------------");
//2.迭代器
Iterator<String> it = list.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
System.out.println("--------------");
//3.增强for循环
for (String s : list) {
System.out.println(s);
}
System.out.println("------------");
//4.Lambda表达式
list.forEach(System.out::println);
}
}
package helloLinkList;
import java.util.LinkedList;
public class Queue {
public static void main(String[] args){
LinkedList<String> queue = new LinkedList<>();
queue.addLast("一号");//队尾入队
queue.addLast("二号");
queue.addLast("三号");
System.out.println(queue);//[一号, 二号, 三号]
queue.removeFirst();//队头出队
queue.removeFirst();
System.out.println(queue);//[三号]
}
}
package helloLinkList;
import java.util.LinkedList;
public class Stack {
public static void main(String[] args){
LinkedList<String> stack = new LinkedList<>();
stack.addFirst("一号子弹");//push进栈从栈顶入
stack.addFirst("二号子弹");
stack.push("三号子弹");//push(e)调用的就是addFirst()
System.out.println(stack);//[三号子弹, 二号子弹, 一号子弹]
stack.removeFirst();//pop出栈从栈顶出
stack.pop();//pop()调用的就是removeFirst()
System.out.println(stack);//[一号子弹]
}
}
package helloSet;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;
public class Test {
public static void main(String[] args){
//HashSet无序,不重复、无索引(其中无序指的是不按照输入的顺序排序)
Set<Integer> set = new HashSet<>();//Set是接口,HashSet是其实现类==>多态
set.add(5);
set.add(6);
set.add(4);
set.add(2);
set.add(5);
set.add(4);
System.out.println(set);//[2, 4, 5, 6] 虽然顺序随机生成,但是一旦确定下来就不会再改变
//LinkedHashSet 有序、不重复、无索引
Set<Integer> set1 = new LinkedHashSet<>();
set1.add(5);
set1.add(6);
set1.add(4);
set1.add(2);
set1.add(5);
set1.add(4);
System.out.println(set1);//[5, 6, 4, 2]
//TreeSet 排序(默认升序)、不重复、无索引
Set<Integer> set2 = new TreeSet<>();
set2.add(5);
set2.add(6);
set2.add(4);
set2.add(2);
set2.add(5);
set2.add(4);
System.out.println(set2);//[2, 4, 5, 6]
}
}
package helloHashSet;
import java.util.HashSet;
import java.util.Set;
public class Test {
public static void main(String[] args){
Set<Student> set = new HashSet<>();
set.add(new Student("刘亦菲", 25, 100));
set.add(new Student("古天乐", 25, 100));
set.add(new Student("吴彦祖", 25, 99));
set.add(new Student("刘亦菲", 25, 100));
System.out.println(set);//[Student{name='古天乐', age=25, score=100.0}, Student{name='刘亦菲', age=25, score=100.0}, Student{name='吴彦祖', age=25, score=99.0}]
Set<Human> set1 = new HashSet<>();
set1.add(new Human("刘亦菲", 123));
set1.add(new Human("古天乐", 124));
set1.add(new Human("吴彦祖", 125));
set1.add(new Human("刘亦菲", 123));
System.out.println(set1);//[Human{name='刘亦菲', id=123}, Human{name='吴彦祖', id=125}, Human{name='古天乐', id=124}, Human{name='刘亦菲', id=123}]
}
}
package helloHashSet;
public class Human {
private String name;
private int id;
public Human() {
}
public Human(String name, int id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Human{" +
"name='" + name + '\'' +
", id=" + id +
'}';
}
}
package helloHashSet;
import java.util.Objects;
public class Student {
private String name;
private int age;
private double score;
public Student() {
}
public Student(String name, int age, double score) {
this.name = name;
this.age = age;
this.score = score;
}
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 double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age && Double.compare(student.score, score) == 0 && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age, score);
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", score=" + score +
'}';
}
}
package helloTreeSet;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
public class Test {
public static void main(String[] args) {
Set<Integer> set1 = new TreeSet<>();
set1.add(3);
set1.add(1);
set1.add(1);
set1.add(2);
System.out.println(set1);//[1, 2, 3]
Set<Student> set2 = new TreeSet<>();
set2.add(new Student("Anna", 12));
set2.add(new Student("Jerry", 15));
set2.add(new Student("John", 11));
set2.add(new Student("Morty", 12));//!“重复”则不保存
System.out.println(set2);//[Student{name='John', age=11}, Student{name='Anna', age=12}, Student{name='Jerry', age=15}]
//TreeSet就近调用自己自带的比较器进行排序
// 原始版本
// Set set3 = new TreeSet<>(new Comparator() {
// @Override
// public int compare(Student1 o1, Student1 o2) {
// return Double.compare(o1.getScore() , o2.getScore());
// }
// });
//简化版本
Set<Student1> set3 = new TreeSet<>((o1, o2) -> Double.compare(o1.getScore() , o2.getScore()));
set3.add(new Student1("Anna", 12, 99.8));
set3.add(new Student1("Jerry", 15, 77.2));
set3.add(new Student1("John", 11, 88.9));
set3.add(new Student1("Morty", 12, 77.2));//!“重复”则不保存
System.out.println(set3);//[Student1{name='Jerry', age=15, score=77.2}, Student1{name='John', age=11, score=88.9}, Student1{name='Anna', age=12, score=99.8}]
}
}
package helloTreeSet;
public class Student implements Comparable<Student>{
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int compareTo(Student o) {//按照年龄,升序输出
return this.getAge() - o.age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
package helloTreeSet;
public class Student1 implements Comparable<Student1>{
private String name;
private int age;
private double score;
public Student1() {
}
public Student1(String name, int age, double score) {
this.name = name;
this.age = age;
this.score = score;
}
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 double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
@Override
public String toString() {
return "Student1{" +
"name='" + name + '\'' +
", age=" + age +
", score=" + score +
'}';
}
@Override
public int compareTo(Student1 o) {
return this.getAge() - o.getAge();
}
}
package helloCollectionExption;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("刘亦菲");
list.add("古天乐");
list.add("刘强东");
list.add("刘金宝");
System.out.println(list);//[刘亦菲, 古天乐, 刘强东, 刘金宝]
//线程错误,报错Exception in thread "main" java.util.ConcurrentModificationException
// Iterator it = list.iterator();
// while(it.hasNext()){
// String name = it.next();
// if(name.contains("刘")){
// list.remove(name);//并发修改异常
// }
// }
Iterator<String> it = list.iterator();
while(it.hasNext()){
String name = it.next();
if(name.contains("刘")){
it.remove();//删除迭代器当前遍历到的数据,每删除一个数据的同时相当于也进行了一次i--操作
}
}
//增强for循环相当于迭代器的简化写法,且没有迭代器方法可用,不能实现
// for(int i = 0; i < list.size(); i++){
// if(list.get(i).contains("刘")){
// list.remove(i);
// i--;//当前元素删除后,下一个顶上来。而顶上来的元素还没有判断过
// }
// }
//或者倒着删也可以
System.out.println(list);//[古天乐]
}
}
package HelloParam;
import java.util.Arrays;
public class Test {
public static void main(String[] args){
//可以不传数据
test();//0 []
//可以传一个或多个数据
test(12);//1 [12]
test(12, 13, 14);//3 [12, 13, 14]
//可以传一个数组
test(new int[]{1, 2, 3, 4, 5});//5 [1, 2, 3, 4, 5]
}
//可变参数:是一种特殊的形参;定义在方法、构造器里的参数列表里;格式:数据类型...参数名
static void test(int...num){//一个形参列表里只能有一个可变参数,且必须是最后一个形参
System.out.println(num.length + " " + Arrays.toString(num));
System.out.println();
}
}
package helloCollections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Test {
public static void main(String[] args){
List<String> list = new ArrayList<>();
//Collections.addAll(Collection, T eles) 为集合批量添加元素
Collections.addAll(list, "刘亦菲", "古天乐", "吴彦祖");
System.out.println(list);//[刘亦菲, 古天乐, 吴彦祖]
//Collections.shuffle(List list)打乱list集合中的元素顺序(Set集合中元素无序,不需要考虑打乱)
Collections.shuffle(list);
System.out.println(list);//[古天乐, 刘亦菲, 吴彦祖]
List<Integer> list1 = new ArrayList<>();
//Collections.sort(List list)对List集合中的元素进行升序排序
Collections.addAll(list1, 4, 1, 2, 3);
Collections.sort(list1);
System.out.println(list1);//[1, 2, 3, 4]
List<Student> list2 = new ArrayList<>();
Collections.addAll(list2, new Student(12, 66), new Student(11, 99), new Student(14, 88));
// Collections.sort(list2, new Comparator() {
// @Override
// public int compare(Student o1, Student o2) {
// return Double.compare(o1.getScore(), o2.getScore());
// }
// });
//Collections.sort(List list, Comparator t)按照比较器对象中的比较规则,对List集合中的元素进行比较
Collections.sort(list2, (o1, o2) -> Double.compare(o1.getScore(), o2.getScore()));
System.out.println(list2);//[Student{age=12, score=66.0}, Student{age=14, score=88.0}, Student{age=11, score=99.0}]
}
}
package helloCollections;
public class Student {
private int age;
private double score;
public Student() {
}
public Student(int age, double score) {
this.age = age;
this.score = score;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
@Override
public String toString() {
return "Student{" +
"age=" + age +
", score=" + score +
'}';
}
}
package helloCollectionApplication;
public class Card {
private String name;
private String color;
private int size;
public Card() {
}
public Card(String name, String color, int size) {
this.name = name;
this.color = color;
this.size = size;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
@Override
public String toString() {
return color + name;
}
}
package helloCollectionApplication;
public class Game {
public static void main(String[] args) {
Room room = new Room();
room.start();
}
}
package helloCollectionApplication;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Room {
List<Card> allCards = new ArrayList<>();
public Room(){
String[] name = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"};
String[] color = {"♥", "♠", "♦", "♣"};
int size = 0;
for(String n : name){
size++;
for(String c : color){
allCards.add(new Card(n, c, size));
}
}
Collections.addAll(allCards, new Card("", "S", ++size), new Card("", "B", ++size));
System.out.println("新牌:" + allCards);
}
public void start(){
//洗牌
Collections.shuffle(allCards);
System.out.println("洗牌后:" + allCards);
//发牌
List<Card> user1 = new ArrayList<>();
List<Card> user2 = new ArrayList<>();
List<Card> user3 = new ArrayList<>();
for(int i = 0; i < allCards.size() - 3; i++){//保留三张地主牌
if(i % 3 == 0) user1.add(allCards.get(i));
else if(i % 3 == 1) user2.add(allCards.get(i));
else user3.add(allCards.get(i));
}
List<Card> lastThreeCard = allCards.subList(allCards.size() - 3, allCards.size());
System.out.println("底牌:" + lastThreeCard);
user1.addAll(lastThreeCard);//默认玩家1叫地主
sortCard(user1);
sortCard(user2);
sortCard(user3);
System.out.println("玩家1手牌:" + user1);
System.out.println("玩家2手牌:" + user2);
System.out.println("玩家3手牌:" + user3);
}
public void sortCard(List<Card> list){
Collections.sort(list, new Comparator<Card>() {
@Override
public int compare(Card o1, Card o2) {
return o1.getSize() - o2.getSize();
}
});
}
}
package helloMap;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
public class Test {
public static void main(String[] args) {
//HashMap:无序、不重复(键)、无索引
Map<String, Integer> map1 = new HashMap<>();
map1.put("刘亦菲", 55);
map1.put("刘亦菲", 34);//相同键值的,最新输入覆盖之前数据
map1.put("古天乐", 40);
map1.put("吴彦祖", 39);
System.out.println(map1);//{刘亦菲=34, 吴彦祖=39, 古天乐=40}
//LinkedHashMap:有序、不重复、无索引
Map<Integer, String> map2 = new LinkedHashMap<>();
map2.put(34, "张亦菲");
map2.put(34, "刘亦菲");//相同键值,保留最新输入
map2.put(12, "古天乐");
map2.put(33, "吴彦祖");
System.out.println(map2);//{34=刘亦菲, 12=古天乐, 33=吴彦祖}
//LinkedHashMap:按键的大小升序、不重复、无索引
Map<Integer, String> map3 = new TreeMap<>();
map3.put(34, "张亦菲");
map3.put(34, "刘亦菲");//相同键值,保留最新输入
map3.put(12, "古天乐");
map3.put(33, "吴彦祖");
System.out.println(map3);//{12=古天乐, 33=吴彦祖, 34=刘亦菲}
Map<String, Integer> map4 = new TreeMap<>();
map4.put("B", 11);
map4.put("z", 9);
map4.put("A", 10);
System.out.println(map4);//{A=10, B=11, z=9} 按照字典序
}
}
package helloMapVisit;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
public class Test {
public static void main(String[] args) {
Map<String, Double> map = new HashMap<>();
map.put("刘亦菲", 100.0);
map.put("古天乐", 98.8);
map.put("吴彦祖", 59.9);
//方法一:键找值
Set<String> set = map.keySet();
for(String name: set){
System.out.println(map.get(name));
}
System.out.println();
//方法二:找键值对
Set<Map.Entry<String, Double>> entries = map.entrySet();
for(Map.Entry<String, Double> entry : entries){
System.out.println(entry.getKey() + ":" + entry.getValue());
}
System.out.println();
//方法三:Lambda表达式
// map.forEach(new BiConsumer() {
// @Override
// public void accept(String s, Double aDouble) {
// System.out.println(s + ":" + aDouble);
// }
// });
// map.forEach((s, aDouble) -> {
// System.out.println(s + ":" + aDouble);
// });
map.forEach((s, aDouble) -> System.out.println(s + ":" + aDouble));
}
}
package helloMapApplication;
import java.util.*;
public class Statis {
public static void main(String[] args){
List<String> list = new ArrayList<>();
String[] group = {"A", "B", "C", "D"};
Random random = new Random();
for(int i = 0; i < 80; i++){
int n = random.nextInt(0,4);
list.add(group[n]);
}
System.out.println(list);//[D, C, D, B, B, C, C, D, A, D, B, D, D, B, B, B, C, D, C, A, C, C, A, B, B, C, A, B, B, B, A, C, D, B, A, B, A, C, D, D, A, B, C, A, C, D, A, A, D, C, C, B, B, A, A, B, D, A, B, B, C,
Map<String, Integer> result = new HashMap<>();
for(String name : list){
if(result.containsKey(name)){//已经包含该组,票数加一
result.put(name, result.get(name) + 1);
}
else{
result.put(name, 1);
}
}
System.out.println(result);//{A=17, B=28, C=21, D=14}
}
}
package hashMap;
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args){
Map<Student, String> map = new HashMap<>();
map.put(new Student("刘亦菲", 25, 99.9), "阳光");
map.put(new Student("古天乐", 25, 100), "开朗");
map.put(new Student("吴彦祖", 25, 98.5), "大男孩");
map.put(new Student("刘亦菲", 25, 99.9), "阳光");
System.out.println(map);//{hashMap.Student@41629346=开朗, hashMap.Student@6d311334=阳光, hashMap.Student@3b07d329=阳光, hashMap.Student@404b9385=大男孩}
Map<Student1, String> map1 = new HashMap<>();
map1.put(new Student1("刘亦菲", 25, 99.9), "阳光");
map1.put(new Student1("古天乐", 25, 100), "开朗");
map1.put(new Student1("吴彦祖", 25, 98.5), "大男孩");
map1.put(new Student1("刘亦菲", 25, 99.9), "阳光");
System.out.println(map1);//{hashMap.Student1@832ddd1=开朗, hashMap.Student1@844b148d=阳光, hashMap.Student1@10114c4a=大男孩}
}
}
package hashMap;
public class Student {
private String name;
private int age;
private double score;
public Student() {
}
public Student(String name, int age, double score) {
this.name = name;
this.age = age;
this.score = score;
}
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 double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
}
package hashMap;
import java.util.Objects;
public class Student1 {
private String name;
private int age;
private double score;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student1 student1 = (Student1) o;
return age == student1.age && Double.compare(student1.score, score) == 0 && Objects.equals(name, student1.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age, score);
}
public Student1() {
}
public Student1(String name, int age, double score) {
this.name = name;
this.age = age;
this.score = score;
}
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 double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
}
package mapNesting;
import java.util.*;
public class Province {
public static void main(String[] args){
Map<String, List<String>> province = new HashMap<>();
List<String> cities1 = new ArrayList<>();
Collections.addAll(cities1, "南京", "连云港", "徐州");
province.put("江苏", cities1);
List<String> cities2 = new ArrayList<>();
Collections.addAll(cities2, "杭州", "宁波", "金华");
province.put("浙江", cities2);
List<String> cities3 = new ArrayList<>();
Collections.addAll(cities3, "厦门", "福州", "泉州");
province.put("福建", cities3);
System.out.println(province);//{福建=[厦门, 福州, 泉州], 浙江=[杭州, 宁波, 金华], 江苏=[南京, 连云港, 徐州]}
List<String> cities = province.get("浙江");
for(String name : cities){
System.out.println(name);
}
province.forEach((p, c) -> System.out.println(p + ":" + c));
/**
福建:[厦门, 福州, 泉州]
浙江:[杭州, 宁波, 金华]
江苏:[南京, 连云港, 徐州]
*/
}
}
package stream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args){
List<String> name = new ArrayList<>();
Collections.addAll(name, "刘亦菲", "古天乐", "刘强东", "刘恒", "吴彦祖");
System.out.println(name);//[刘亦菲, 古天乐, 刘强东, 刘恒, 吴彦祖]
//方法一(老方法)
List<String> selectName1 = new ArrayList<>();
for(String n : name){
if(n.startsWith("刘") && n.length() == 3) selectName1.add(n);
}
System.out.println(selectName1);//[刘亦菲, 刘强东]
//stream流
List<String> selectName2 = name.stream().filter(s -> s.startsWith("刘"))
.filter(a -> a.length() == 3).collect(Collectors.toList());
System.out.println(selectName2);//[刘亦菲, 刘强东]
}
}
package stream;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Get {
public static void main(String[] args){
//获取list中的Stream流
List<String> list = new ArrayList<>();
Collections.addAll(list, "刘亦菲", "古天乐", "吴彦祖");
Stream<String> stream1 = list.stream();
//获取Set中的Stream流
Set<String> set = new HashSet<>();
Collections.addAll(set, "刘亦菲", "古天乐", "吴彦祖");
Stream<String> stream2 = set.stream();
//获取Map中的Stream流
Map<String, Integer> map = new HashMap<>();
map.put("刘亦菲", 100);
map.put("古天乐", 99);
map.put("吴彦祖", 101);
Stream<String> stream3 = map.keySet().stream();
Stream<Integer> stream4 = map.values().stream();
Stream<Map.Entry<String, Integer>> stream5 = map.entrySet().stream();
stream5.filter(s -> s.getKey().endsWith("乐")).forEach(e -> System.out.println(e.getKey() + ";" + e.getValue()));//古天乐;99
//获取数组中的Stream流
String[] name = {"刘亦菲", "古天乐", "吴彦祖"};
Stream<String> stream6 = Arrays.stream(name);
Stream<String> stream7 = Stream.of(name);
}
}
package stream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class HelloMethod {
public static void main(String[] args){
//需求1:找出大于等于60的成绩,并升序输出
List<Double> scores = new ArrayList<>();
Collections.addAll(scores, 100.0, 49.9, 72.3, 61.6);
scores.stream().filter(s -> s >= 60).sorted()
.forEach(s -> System.out.print(s + " "));//61.6 72.3 100.0
System.out.println();
//需求2:找出年龄在20-50之间的学生,并按照年龄升序输出
List<Student> students = new ArrayList<>();
Collections.addAll(students, new Student("刘亦菲", 30, 100.0)
, new Student("古天乐", 25, 95)
, new Student("吴彦祖", 29, 99)
,new Student("费雯丽", 55, 150)
,new Student("费雯丽", 55, 150));
students.stream().filter(s -> s.getAge() >= 20 && s.getAge() <= 50)
.sorted((o1, o2) -> o1.getAge() - o2.getAge())
.forEach(s -> System.out.println(s));
/**Student{name='费雯丽', age=55, score=150.0}
Student{name='费雯丽', age=55, score=150.0}
Student{name='刘亦菲', age=30, score=100.0}*/
System.out.println();
//需求3:取出成绩前三高的学生,并输出
students.stream().sorted((o1, o2) -> Double.compare(o2.getScore(), o1.getScore()))
.limit(3).forEach(s -> System.out.println(s));
System.out.println();
//需求4:取出成绩倒二的学生,并输出
students.stream().sorted((o1, o2) -> Double.compare(o2.getScore(), o1.getScore()))
.skip(students.size() - 2).forEach(s -> System.out.println(s));
System.out.println();
//需求5:取出成绩超过95的学生,并输出其名字,要求不重复
students.stream().filter(s -> s.getScore() > 95).map(s -> s.getName()).distinct()
.forEach(s -> System.out.println(s));
System.out.println();
//distinct()去重。当对象为自定义时,若希望内容一样则相同,需要重写equals()和hashCode()方法
students.stream().filter(s -> s.getScore() > 95).distinct()
.forEach(s -> System.out.println(s.getName()));
System.out.println();
//concat()合并
Stream<String> stream1 = Stream.of("刘亦菲", "古天乐");
Stream<String> stream2 = Stream.of("吴彦祖");
Stream<String> allStream = Stream.concat(stream1, stream2);
allStream.forEach(System.out::println);
//不同类型合并,合并的类型用Object
Stream<String> stream3 = Stream.of("刘亦菲", "古天乐");
Stream<Integer> stream4 = Stream.of(2, 1, 3);
Stream<Object> allStream1 = Stream.concat(stream3, stream4);
allStream1.forEach(s -> System.out.println(s));
}
}
package stream;
import java.util.*;
import java.util.stream.Collectors;
public class Final {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
Collections.addAll(students, new Student("刘亦菲", 30, 100.0)
, new Student("古天乐", 25, 95)
, new Student("吴彦祖", 29, 99)
,new Student("费雯丽", 55, 150)
,new Student("费雯丽", 54, 150));
System.out.println(students);
//需求1:计算成绩超过95的人数
long size = students.stream().filter(s -> s.getScore() > 95).count();
System.out.println(size);//4
//需求2:找出成绩最好的学生,并输出
Student max = students.stream()
.max((o1, o2) -> Double.compare(o1.getScore(), o2.getScore())).get();
System.out.println(max);//并列最大时,选择首次出现的
//需求3:找出成绩最差的学生,并输出
Student min = students.stream()
.min((o1, o2) -> Double.compare(o1.getScore(), o2.getScore())).get();
System.out.println(min);
//需求4:找出成绩超过95的学生,并放到集合中
List<Student> highScore = students.stream().filter(s -> s.getScore() > 95).collect(Collectors.toList());
System.out.println(highScore);
//!!!流只能收集一次,可以理解为一个迭代器,指针已经指到了最后
Set<Student> highScore1 = students.stream().filter(s -> s.getScore() > 95).collect(Collectors.toSet());
System.out.println(highScore1);
//需求5:找出成绩超过95的学生,并把名字和成绩放到Map中返回
Map<String, Double> highScore2 = students.stream().filter(s -> s.getScore() > 95)
.collect(Collectors.toMap(s -> s.getName(), s -> s.getScore(), (a, b) -> a));//第三个参数处理键值重复情况下的取舍规则,例如本次取先出现的
System.out.println(highScore2);
Object[] highScore3 = students.stream().filter(s -> s.getScore() > 95).toArray();
System.out.println(Arrays.toString(highScore3));
Student[] highSocre4 = students.stream().filter(s -> s.getScore() > 95).toArray(num -> new Student[num]);
System.out.println(Arrays.toString(highSocre4));
}
}
package exam;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
public class T1 {
public static void main(String[] args) {
Map<Integer, Integer> person = new TreeMap<>();
Random r = new Random();
int[] del = new int[205];
//占位
int n, size = 1, k = 0, leave = 100, pos;
for (int i = 0; i < 100; i++) {
while (true) {
n = r.nextInt(1, 201);
if (!person.containsKey(n)) {
person.put(n, 1);
del[k++] = n;
break;
}
}
person.replace(n, size++);
}
//删除奇数位置
while (leave > 1) {
pos = 1;
for (int i = 0; i < del.length; i++) {
if (del[i] != 0) {//改编号成员未删除
if(pos % 2 == 1){
person.remove(del[i]);
del[i] = 0;
}
pos++;
}
}
leave = 0;
for(int i = 0; i < del.length; i++)
if(del[i] != 0) leave++;
}
for(int i = 0; i < del.length; i++)
if(del[i] != 0){
System.out.println(del[i] + "," + person.get(del[i]));//编号
}
}
}
package exam;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class T1_1 {
private static List<Person> persons = new ArrayList<>();
public static void main(String[] args) {
Random r = new Random();
for(int i = 0; i < 100; i++){
int num = r.nextInt(1, 201);
while(true){
num = r.nextInt(1, 201);
if(isExist(num) == false){
persons.add(new Person(num, i + 1));
break;
}
}
}
while(persons.size() > 1){
List<Person> keepPeople = new ArrayList<>();
for(int i = 1; i < persons.size(); i+= 2){
keepPeople.add(persons.get(i));
}
persons = keepPeople;
}
System.out.println(persons.get(0));
}
private static boolean isExist(int num){
for(Person p : persons){
if(p.getNum() == num) return true;
}
return false;
}
}
package exam;
public class Person {
private int num;
private int firstPos;
public Person() {
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int getFirstPos() {
return firstPos;
}
public void setFirstPos(int firstPos) {
this.firstPos = firstPos;
}
public Person(int num, int firstPos) {
this.num = num;
this.firstPos = firstPos;
}
@Override
public String toString() {
return "Person{" +
"num=" + num +
", firstPos=" + firstPos +
'}';
}
}
package exam;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class T1_2 {
public static void main(String[] args) {
List<Integer> persons = new ArrayList<>();
Random r = new Random();
for(int i = 1; i < 101; i++){
while(true){
int n = r.nextInt(1, 201);//int n = r.nextInt(200) + 1;
if(persons.contains(n) == false){
persons.add(n);
break;
}
}
}
List<Integer> persons1 = persons;
while(persons1.size() > 1){
List<Integer> temp = new ArrayList<>();
for(int i = 1; i < persons1.size(); i += 2) temp.add(persons1.get(i));
persons1 = temp;
}
System.out.println(persons1.get(0) + "," + persons.indexOf(persons1.get(0)));
}
}
package exam;
import java.time.LocalDate;
import java.util.*;
public class T2 {
public static void main(String[] args) {
List<User> users = new ArrayList<>();
String data = "1001:刘亦菲:女:1990-01-02#1002:古天乐:男:1998-01-02#1003:吴彦祖:男:1997-02-04#1002:古天乐:男:1998-01-02#1002:古天乐:男:1998-01-02";
String[] info = data.split("#");
for (int i = 0; i < info.length; i++) {
String[] singleInfo = info[i].split(":");
users.add(new User(Long.valueOf(singleInfo[0]), singleInfo[1], singleInfo[2]
, LocalDate.parse(singleInfo[3])));
}
Map<String, Integer> size = new HashMap<>();
for(User user : users){
String name = user.getName();
if(size.containsKey(name)) size.replace(name, size.get(name) + 1);
else{
size.put(name, 1);
}
}
size.forEach((k, v) -> {
System.out.println(k + ":" + v);
});
}
}
package exam;
import java.time.LocalDate;
public class User {
private long id;
private String name;
private String gender;
private LocalDate birthday;
public User() {
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", gender='" + gender + '\'' +
", birthday=" + birthday +
'}';
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public LocalDate getBirthday() {
return birthday;
}
public void setBirthday(LocalDate birthday) {
this.birthday = birthday;
}
public User(long id, String name, String gender, LocalDate birthday) {
this.id = id;
this.name = name;
this.gender = gender;
this.birthday = birthday;
}
}
package exam;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
public class T3 {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2022, 2, 3);
int year, month, n = 0;
Scanner sc = new Scanner(System.in);
System.out.println("输入查询时间:");
String date = sc.next();
String[] date1 = date.split("-");
year = Integer.parseInt(date1[0]);
month = Integer.parseInt(date1[1]);
LocalDate searchL = LocalDate.of(year, month, 1), flag = searchL;
while(start.isBefore(searchL)){
start = start.plusDays(1);
n++;
}
n++;//加一后才是给定日期月初
while(searchL.getMonth() == flag.getMonth()){
if(n % 2 == 0) {
if(searchL.getDayOfWeek().getValue() == 6 || searchL.getDayOfWeek().getValue() == 7){
System.out.print(searchL + "[休息]" + (searchL.getDayOfWeek().getValue() == 6 ? "周六" : "周日") + " ");
}
else System.out.print(searchL + "[休息] ");
}
else System.out.print (searchL + " ");
searchL = searchL.plusDays(1);
n++;
}
System.out.println();
//六级倒计时
String examTime = "2023-12-16 14:40:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime examTime1 = LocalDateTime.parse(examTime, formatter);
LocalDateTime now = LocalDateTime.now();
Duration duration = Duration.between(examTime1, now);
System.out.println(duration.toDays() + "天" + duration.toHoursPart() + "时"
+ duration.toMinutesPart() + "分钟" + duration.toSecondsPart() + "秒");
}
}
package exam;
import java.util.ArrayList;
public class T4 {
public static void main(String[] args) {
MyArrayList<String> myList = new MyArrayList<>();
myList.add("刘亦菲");
myList.add("古天乐");
myList.add("吴彦祖");
System.out.println(myList);
System.out.println(myList.size());
myList.foreach(s -> System.out.println(s));
System.out.println(myList.remove(1));;
System.out.println(myList.get(1));
System.out.println(myList);
}
}
package exam;
import java.util.Arrays;
public class MyArrayList <E>{//需要支持泛型
private Object[] elements = {};//内部使用数组作为容器
private int size;//记录长度,同时也记录下一个可存放位置
private int DEFAULT_CAPACITY = 10;//初始默认长度
//添加元素
public void add(E e){
if(size == elements.length) grow();
elements[size++] = e;
}
//扩容
public void grow(){
if(size == 0) elements = new Object[DEFAULT_CAPACITY];
else elements = Arrays.copyOf(elements,
elements.length + elements.length >> 1);
}
//根据索引查询数据
public E get(int index){
checkIndex(index);
return (E) elements[index];
}
//检查索引是否合法
public void checkIndex(int index){
if(index < 0 || index >= size){
throw new IndexOutOfBoundsException(index + " out of length");
}
}
//删除指定索引处的数据
public E remove(int index){
checkIndex(index);
E del = (E) elements[index];
for(int i = index; i < size; i++){
elements[i] = elements[i + 1];
}
elements[--size] = null;
return del;
}
//获得集合长度
public int size(){
return size;
}
//实现foreach()遍历
public void foreach(MyConsumer<E> action){
if(action == null) throw new NullPointerException();
for(int i = 0; i < size; i++){
action.accept((E) elements[i]);
}
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("[");
for(int i = 0; i < size; i++){
stringBuilder.append(elements[i]).append(i == size - 1 ? "" : ", ");
}
stringBuilder.append("]");
return stringBuilder.toString();
}
}
package exam;
@FunctionalInterface
public interface MyConsumer<E> {
void accept(E e);
}
package exam;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class T5 {
public static void main(String[] args){
int[] arr = {1, 2, 3, 3, 3, 3, 5};
int target = 3;
System.out.println(getPos(arr, target, 0) + "," + getPos(arr, target, 1));
}
public static int getPos(int[] nums, int target, int flag){
int left = 0, right = nums.length, mid, ans = -1;
while(left <= right){
mid = (left + right) / 2;
if(nums[mid] == target){
ans = mid;
if(flag == 0) right = mid - 1;
else left = mid + 1;
}
else if(nums[mid] > target) right = mid - 1;
else left = mid + 1;
}
return ans;
}
}
package exam;
public class T6 {
public static void main(String[] args){
MyLinkedList<String> myList = new MyLinkedList<>();
MyLinkedList.Node<String> head = myList.add();
myList.foreach(head);
}
}
package exam;
import java.util.Scanner;
public class MyLinkedList <E>{
public Node<E> add(){
Node<E> h = null, rear = null;
Scanner sc = new Scanner(System.in);
String data = sc.next();
while(!data.equals("exit")){
Node node = new Node(data, null);
if(h == null){
h = rear = node;
}
else{
rear.next = node;
rear = node;
}
data = sc.next();
}
return h;
}
public void foreach(Node<E> head){
if(head == null){
System.out.println(head);
return;
}
while(head != null){
System.out.println(head);
head = head.next;
}
}
//定义内部类,作为链表节点
static class Node<E>{
E data;
Node<E> next;
public Node(E data, Node<E> next) {
this.data = data;
this.next = next;
}
@Override
public String toString() {
return "Node{" +
"data=" + data +
'}';
}
}
}
package file;
import java.io.File;
import java.text.SimpleDateFormat;
public class FileInfo {
public static void main(String[] args){
//创建文件对象,指代某个文件
File file1 = new File("IO");
File file2 = new File("IO/");
File file3 = new File("IO/src/fileTest.txt");
File file4 = new File("IO/src1/fileTest.txt");
File file5 = new File("C:\\summer\\needHungry\\code\\java\\eclipse-workspace\\JavaEnhance\\IO\\src\\fileTest.txt");
//boolean exists()判断当前文件对象,对应的文件路径是否存在,存在则返回true
System.out.println(file3.exists());//true
System.out.println(file4.exists());//false
//boolean isFile()判断当前文件对象,是否为文件,是则返回true
System.out.println(file1.isFile());//false
System.out.println(file2.isFile());//false
System.out.println(file3.isFile());//true
System.out.println(file4.isFile());//false
//boolean isDirectory()判断当前文件对象,是否为文件夹,是则返回true
System.out.println(file1.isDirectory());//true
System.out.println(file2.isDirectory());//true
System.out.println(file3.isDirectory());//false
System.out.println(file4.isDirectory());//false
//String getName() 获取文件名称(若有后缀,则也包含后缀)
System.out.println(file1.getName());//IO
System.out.println(file2.getName());//IO
System.out.println(file3.getName());//fileTest.txt
System.out.println(file4.getName());//fileTest.txt
//long length()获取文件长度,单位为字节
System.out.println(file3.length());//4
//long lastModified()获取文件的最后修改时间,单位是毫秒值
long time = file3.lastModified();
System.out.println(time);//1698317778574
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
System.out.println(sdf.format(time));//2023-10-26 18-56-18
//String getPath()获取创建文件对象时,使用的路径
System.out.println(file3.getPath());//IO\src\fileTest.txt
System.out.println(file5.getPath());//C:\summer\needHungry\code\java\eclipse-workspace\JavaEnhance\IO\src\fileTest.txt
//String getAbsolutePath()获取绝对路径
System.out.println(file3.getAbsolutePath());//C:\summer\needHungry\code\java\eclipse-workspace\JavaEnhance\IO\src\fileTest.txt
System.out.println(file5.getAbsolutePath());//C:\summer\needHungry\code\java\eclipse-workspace\JavaEnhance\IO\src\fileTest.txt
}
}
package file;
import java.io.File;
import java.io.IOException;
public class CreateAndDel {
public static void main(String[] args) throws IOException {
//boolean createNewFile()创建一个新文件,初始文件为空,创建成功则返回true
File file1 = new File("IO\\src\\createTest.txt");
System.out.println(file1.createNewFile());//true
//boolean mkdir()用于创建文件夹,注意只能创建一级文件夹
File file2 = new File("IO\\src\\files");
System.out.println(file2.mkdir());//true
//boolean mkdirs()用于创建文件夹,注意可以创建多级文件夹
File file3 = new File("IO\\src\\files\\aa\\bb\\cc");
File file4 = new File("IO\\src\\files\\dd");
System.out.println(file3.mkdirs());//true
System.out.println(file4.mkdirs());//true
//boolean delete()删除文件或空的文件夹,注意不能删除为空文件夹。删除后的文件不会进入回收站
System.out.println(file4.delete());//true
System.out.println(file1.delete());//true
}
}
package file;
import java.io.File;
public class VisitDirectory {
public static void main(String[] args){
//String[] list()获取当前目录下所有的一级文件名称,到一个字符串数组中返回
File file1 = new File("IO\\src\\files");
String[] directory = file1.list();
for(String d : directory){
System.out.println(d);
}
//File[] listFiles()获取当前目录下所有的一级文件对象,到一个文件对象数组中返回
File[] files = file1.listFiles();
for(File f : files){
System.out.println(f.getAbsolutePath());
}
}
}
package file;
import java.io.File;
public class SearchFile {
public static void main(String[] args){
File dir = new File("IO\\src\\files");
String fileName = "3.txt";
String fileName1 = "4.txt";
if(!searchFile(dir, fileName)) System.out.println("查找失败");//目标文件位于C:\summer\needHungry\code\java\eclipse-workspace\JavaEnhance\IO\src\files\3.txt
if(!searchFile(dir, fileName1)) System.out.println("查找失败");//查找失败
}
/**
* 在目录中搜索某个文件
* @param dir 目录
* @param fileName 要搜索的文件名
*/
public static boolean searchFile(File dir, String fileName){
//拦截非法情况
if(dir == null || !dir.exists() || dir.isFile()) return false;
File[] files = dir.listFiles();
if(files != null && files.length > 0){
for(int i = 0; i < files.length; i++){
if(files[i].isFile()){
if(files[i].getName().contains(fileName)){
System.out.println("目标文件位于" + files[i].getAbsolutePath());
return true;
}
else return false;
}
else searchFile(files[i], fileName);
}
}
return false;
}
}
package file;
import java.io.File;
public class DelDir {
public static void main(String[] args){
File drc = new File("IO\\src\\files");
if(delDir(drc)) System.out.println("delete successfully");
else System.out.println("delete failed");
}
/**
* 删除给定文件夹
* @param drc 目标文件夹
*/
public static boolean delDir(File drc){
//拦截非法情况
if(drc == null || !drc.exists()) return false;
if(drc.isFile()){
drc.delete();
return true;
}
File[] files = drc.listFiles();
if(files != null && files.length > 0){
for(int i = 0; i < files.length; i++){
if(files[i].isFile()) files[i].delete();
else {
File[] tFiles = files[i].listFiles();
if(tFiles.length == 0) files[i].delete();
else delDir(files[i]);
}
}
}
drc.delete();
return true;
}
}
package charset;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
public class Test {
public static void main(String