文章目录
一、java SE(上篇)
示例:java是做后台服务器程序,c和c++是做本地应用程序。(安卓、服务器程序)
API接口
1.什么是JDK API
- 工具 ,应用程序编程接口
2.JDK包结构 - 包分类、解决类的命名冲突
- java.lang 包很基础,不用import
- java.io 、java.net、java.sql用的多
文档注释
- 文档注释可以通过javadoc工具 转换为HTML文档,普通无法通过工具生成文档。
4.文档注释规范 - 功能说明、@author、@version、@see、 @since。
- 文档注释可以写在类、方法、常量上
5.javadoc命令生成文档 - 可以通过IDEA软件直接生成
字符串
1.字符串的本质是字符数组
- C 没有String 类型 ,需要使用 字符数组来写 char[ ] name = new char[10]; name[0]= ‘1’;…
- String str = “hello world!”;
- 鼠标选中 Sting 然后 按 Ctrl + 右键
public class Sting {
public static void main(String[] args) {
String str = "hello world!";
}
}
2.String是不可变对象
- 字符串一旦对应,对象是不变的
- 基本数据类型: boolean、 byte、 char、 short、 int、 long、 float、 double 8种,特点:变量保存的是值本身。
- 引用数据类型:数组、类 、枚举等 除了8种基础类型都是引用类型。包括Sting ,在内存是对象,既堆里的一块存储区域。特点:引用型变量定义的是对象在内存中的地址。
- String str = “hello world!”; 在堆中创建 “hello world”的对象,对象一旦创建,对象的内容是永远 不会改变的。Sting 天生被final 修饰。 如果重新赋值的话只是会产生一个新的对象。引用指向了新的对象,老的对象等着被回收站回收。
2.String的特征 - 计算机存取的字符串最大为 65536个
- 字符串不能被继承
- 字符串一旦创建,对象永远无法改变
- 字符串内部 1个字符 是2个字节,因为char类型(2字节)
3.String的两种表示方法
public class Sting {
public static void main(String[] args) {
String str = "hello world!"; //字面量
String str1 = new String("hello word"); //·String 是对象,正宗的表示方法
}
}
4.String的常量池
- 程序中因为存在大量重复的字符串,JAVA前辈所以做的优化,当字符串相同时实现了共用。
public class Sting {
public static void main(String[] args) {
String str = "hello world!";
String str1 = "hello world!";
}
}
- 缺点:字符串一旦修改频繁,不利(GC频繁的回收)。
public class Sting {
public static void main(String[] args) {
String str = "123hello world!";
String str1 = "123hello world!";
/*
编译器小特性:
当一个表达式运算两边都是字面量,那么编译的过程 就会进行计算,将结果生成在表达式的
位置,可以节省运算时的开销
* */
String str3 = "123" + "hello world!";
String str4 = 1+23+"hello world!";
String str5 = 1+"23"+"hello world!";
String str6 = "1"+23+"hello world!";
String str7 = 1+'2'+"3"+"hello world!";
/*
* new 表示创建新对象,只有使用字面量赋值才会
* 使用常量池中原来的对象进行重用
*
* */
String str8 = new String("123Hello world!");
//String str3 = "123hello world!";
System.out.println(str == str1); //true
System.out.println(str3 == str1);//true
System.out.println(str4 == str1);//false
System.out.println(str5 == str1);//true
System.out.println(str6 == str1);//true
System.out.println(str7 == str1);//false
System.out.println(str8 == str1);//false
}
}
String的基本方法
1.indexOf方法
public class Sting1 {
public static void main(String[] args) {
// 0123456789012345
String str = "thinking in java";
int index = str.indexOf("in");
System.out.println("index:" + index);//2
/*
* indexOf(String str,int index)
* 查找第一个参数要在当前字符串中找到
* 然后返回第一个字母所在下标的位置
*/
index = str.indexOf("in",3);
System.out.println("index:" + index);//5
/*
*查找最后一次出现 参数的位置
*/
index = str.lastIndexOf("in");
System.out.println("index:"+index);//9
//email
String mail = "123123123.com";
index = mail.indexOf("@");
if (index <= 0 || index >= (mail.length()-1)){
System.out.println("不是邮箱");
} else{
System.out.println("是邮箱");
}
}
}
2.substring方法
/**
* String subString(int start,int end)
* 截取当前字符串的部分内容
*
*/
public class String2 {
public static void main(String[] args) {
// 012345678901234567890
/*
*使用数字表示范围,java都是含头不含尾
*/
String str = "http://www.oracle.com";
String subs = str.substring(11, 17); //oracle
System.out.println(subs);//oracle.com
/*
*切一刀取后面
*/
subs = str.substring(11);
System.out.println(subs);
/*
*www.oracle.com
* 获取域名
* 思路:
* 1:获取第一个"."的位置,对其+1后就是后面的第一个
* 字符的位置
* 2:获取第二个"."的位置
*/
int start = str.indexOf(".");
int end = str.indexOf(".",start + 1);
subs = str.substring(start + 1, end);
System.out.println(subs);
}
}
3.charAt方法
/**
* 或者指定位置的字符
* char charAt(int index)
*/
public class String4 {
public static void main(String[] args) {
// 012345678
String str = "helloword";
char c = str.charAt(5);
System.out.println(c);
/*
*检查回文
* 上海自来水来自海上
* 思路:
* 1:循环判断
* 2:正数位置上的字符与倒数位置的字符都一样
*/ //01 2 34 5 6 7 8
str = "上海自来水来自海上";
for(int i=0;i<str.length()/2;i++){
if(str.charAt(i) != str.charAt(str.length() -1-i)){
System.out.println("不是回文");
return;
}
}
System.out.println("是回文");
}
}
4.startsWith 和 endsWith方法
/*
*判断当前字符串是否是以给定的字符串开头或结尾的
* boolean startsWith(String str)
* boolean endsWith(String str)
*/
public class String5 {
public static void main(String[] args) {
String str = "ThinKing IN Java";
boolean starts = str.startsWith("Thi");
if(starts){
System.out.println("开头"); //开头
}else{
System.out.println("不是开头");
}
boolean ends = str.endsWith(" Java");
if(ends){
System.out.println("结尾"); //结尾
}else{
System.out.println("不是结尾");
}
}
}
5.toUpperCase() 和 toLowerCase方法
import java.util.Random;
import java.util.Scanner;
/*
*将当前字符串中英文部分转换为全大写或全小写
* String toUpperCase()
* String toLowerCase()
*/
public class String6 {
public static void main(String[] args) {
String str = "我爱Java";
String upper = str.toUpperCase();
System.out.println(upper); //我爱JAVA
String lower = str.toLowerCase();
System.out.println(lower); //我爱java
//应用 :验证码
//1、产生验证码
StringBuilder s = new StringBuilder();
Random random = new Random();
for(int i= 0;i<5;i++){
int num = random.nextInt(3);
switch (num){
case 0:char r = (char) ((char)random.nextInt(26)+'a');
s.append(r);
break;
case 1:char r1 = (char) ((char)random.nextInt(26)+'A');
s.append(r1);
break;
case 2: s.append(random.nextInt(10));
break;
}
}
//验证验证码
System.out.println("请输入验证码:" + s);
Scanner sc = new Scanner(System.in);
String input = sc.next();
s = new StringBuilder(s.toString().toLowerCase());
input =input.toLowerCase();
if(s.toString().equals(input)){
System.out.println("验证成功");
}else{
System.out.println("验证失败");
}
}
}
5.trim() 方法
/*
*去除字符串两边空白
* String trim()
*/
public class String3 {
public static void main(String[] args) {
String str = " hello world ";
String trim =str.trim();
System.out.println(str); // hello world
System.out.println(trim);//hello world
}
}
//应用:取出url的空白 或者密码的空白
5.valueOf方法
/**
* valueOf() 有多种重载形式
* 常用将8种基本类型转换为字符串类型
*/
public class String7 {
public static void main(String[] args) {
int i = 100;
double d = 152.365;
String is = String.valueOf(i);
String ds = is + d;
System.out.println(ds); //100152.365
String str = 100 + "";
System.out.println(str); //100
}
}
StringBuilder及其API
- 由于字符串是固定不变的,不适合频繁修改,因此JAVA中有一个类StringBuilder是专门用来修改字符串的,其本身不是字符串,优点是节省内存空间。比如修改了字符串"a" +=“a”,对于字符串而言,需要再创建一个新的对象。单对于StringBuilder而言,不需要再创建一个新的字符串,而是在老的对象后面追加一个a。✌
1.常用方法-增删改插
/**
* StringBuilder 用于解决字符串频繁修改带来的内存消耗
* 所以将来我们频繁修改字符串的内容这样的操作时,首先使用
* StringBuilder
*/
public class StringBuilderDome {
public static void main(String[] args) {
//内部默认为空字符串
StringBuilder builder = new StringBuilder();
//内部默认为字符串:hello world
//StringBuilder builder1 = new StringBuilder("hello world");
//append 追加
// 01 2 3 4 56 7 8 9 01 2 3 4 5
builder.append("努力学大数据开发,为了找个好工作");
String str = builder.toString();
System.out.println(str);
//replace 替换
builder.replace(9,16,"为了改变世界");
str = builder.toString();
System.out.println(str);
//delete 删除
builder.delete(0,8);
str = builder.toString();
System.out.println(str);
//活着,为了改变世界
builder.insert(0,"活着"); //从 0开始往后移
/* str = builder.toString();
System.out.println(str);*/
//简写优化,从下之上,等量代换
System.out.println(builder.toString());
}
}
运行结果:
努力学大数据开发,为了找个好工作
努力学大数据开发,为了改变世界
,为了改变世界
活着,为了改变世界
Process finished with exit code 0
2.return this
3.** reverse **
/**
* reverse 字符串反转
*/
public class StringBuilderDemo1 {
public static void main(String[] args) {
String str = "上海自来水来自海上";
StringBuilder builder = new StringBuilder(str);
builder = builder.reverse();
String str2 = builder.toString();
System.out.println(str2); //上海自来水来自海上
if(str.equals(str2)){ //是回文
System.out.println("是回文");
}else {
System.out.println("不是回文");
}
}
}
4.Stringbuffer 和 StringBuilder
5.汉字的unicode编码
汉字的起始:char c = ‘\u4e00’;
汉子的结束:char c = ‘\u9fa5’
public class hanzi {
public static void main(String[] args) {
char c = '\u4e00';
for(int i=0;i<10;i++){
c+=i;
System.out.print(c + " ");
}
}
}
一 丁 七 丆 上 丏 丕 东 两 中
正则表达式
1.正则表达式
什么是正则表达式:用一组特殊的字符描述的一个字符串格式,作用是匹配一个字符串是否满足格式要求。只关注格式是否正确,不关心内容是否有效
2.常见的正则表达式
(+\86)?13512345678
^ [0-9]{11}$ :^ 开始 $ 结束
3.使用matches( ) 方法匹配
* boolean matches(String regex)
* 使用给定的正则表达式验证当前字符串是否满足
* 格式要求,满足返回true
* 字符串matches 方法是全匹配的
4.举例验证邮箱和身份证号
/**
* 字符串支持正则表达式的方法1:
* 匹配格式
*/
public class StringDemo1 {
public static void main(String[] args) {
/*
* 邮箱地址
* [a-zA-Z0-9_]+@[a-zA-Z0-9_]+(\.[a-zA-Z0-9])+
*/
String regex = "[a-zA-Z0-9_]+@[a-zA-Z0-9_]+(.[a-zA-Z0-9])+";
System.out.println(regex);
String email = "lzdeng103@fiberhome.com";
/*
* boolean matches(String regex)
* 使用给定的正则表达式验证当前字符串是否满足
* 格式要求,满足返回true
*/
boolean match = email.matches(regex);
System.out.println(match);
if(match){
System.out.println("是邮箱");
}else{
System.out.println("不是邮箱");
}
}
}
/**
* 身份证号验证
*/
public class StringDemo2 {
public static void main(String[] args) {
/*
* \d{15}(\d{2}[0-9xX])?
*/
String regex = "\\d{15}(\\d{2}[0-9xX])?";
String id = "42232619950512641x";
boolean math = id.matches(regex);
if(math){
System.out.println("身份证号正确!");
}else{
System.out.println("身份证号有误!");
}
}
}
5.Split方法的作用
练习:
/**
* String split(String regex)
* 当钱字符串满足正则表达式的部分拆分
*
*/
public class StringDemo3 {
public static void main(String[] args) {
String str = ",,,boss,jack,,marry,jackson,,,";
String [] arr = str.split(",");
System.out.println(arr.length);
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
}
运行结果:
8
boss
jack
marry
jackson
6.replaceAll方法
练习:
```java
/**
* 将字符串中满足正则表达式的部分替换成给定的内容
* String replaceAll(String regex,String replace)
*/
public class StringDemo4 {
public static void main(String[] args) {
String str = "ab123lask123123dflk9824kj94kj0909";
str = str.replaceAll("\\d+","#num#");
System.out.println(str);
}
}
运行结果:
ab#num#lask#num#dflk#num#kj#num#kj#num#
/**
* 作用:游戏里的 用来和谐的 你个**
*/
object
1.所有类都继承自object,因为所有的类都是对象
2.toString方法
public class Teacher {
private String name;
private int age;
private String gender;
public static void main(String[] args) {
Teacher p = new Teacher();
p.name = "哇哈哈";
p.age = 10;
p.gender = "男";
/* String str = p.toString();
System.out.println(str);*/
/*
*System.out.println(Object obj)
* 将给定对象的toString()方法返回的字符串
* 输出到控制台
*/
System.out.println(p);
}
public String toString(){
return name+","+age+","+gender;
}
}
哇哈哈,10,男
3.equals方法
- == 比较的是是否为同一个对象
- equals 比较两个对象像不像
public class Teacher {
private String name;
private int age;
private String gender;
public static void main(String[] args) {
Teacher p = new Teacher();
p.name = "哇哈哈";
p.age = 10;
p.gender = "男";
/* String str = p.toString();
System.out.println(str);*/
/*
*System.out.println(Object obj)
* 将给定对象的toString()方法返回的字符串
* 输出到控制台
*/
System.out.println(p);
Teacher p2 = new Teacher();
p2.name = "哇哈哈";
p2.age = 10;
p2.gender = "男";
System.out.println(p==p2); //false
System.out.println(p.equals(p2)); //true ,如果没有重写则返回的是false
}
public String toString(){
return name+","+age+","+gender;
}
/*
*改方法用来判断当前对象与给定的对象"长得像不像"
* 比较内容(属性)
*/
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if(obj instanceof Teacher){
Teacher t = (Teacher)obj;
return t.name.equals(this.name)
&&
t.age == this.age
&&
t.gender.equals(this.gender);
}
return false;
}
}
基本类型包装类
1.包装类概述
int —Integer char -Character
包装类都是final的不能再定义子类
/**
* 包装类
* 用于使基本类型可以参与面向对象开发
*/
public class IntegerDemo {
public static void main(String[] args) {
Integer i = new Integer(1);
Double d = new Double(1.2);
Short s = new Short((short) 1);
Byte b = 1;
}
public static void dosome(Object obj){}
}
2.Number类及其主要方法
public class IntegerDome2 {
public static void main(String[] args) {
Double d = 123.456;
double dd = d.doubleValue();
System.out.println(dd);
int i = d.intValue();
System.out.println(i);
short s = d.shortValue();
System.out.println(s);
byte b = d.byteValue();
System.out.println(b);
}
}
123.456
123
123
123
3.编译器对包装类的支持
4.Integer和Double常用方法之 MAX_VALUE, MIN_VALUE, parselnt(“123”),parseDouble(“123.456”),toBinaryString(100)在这里插入代码片
,toHexString(100)
Date和DateFormat
1.Date类及其常用方法
import java.util.Date;
/**
* java.util.Date
* 该类的每一个实例用于表示一个时间
*/
public class DateDome {
public static void main(String[] args){
/*
*默认表示当前系统时间
*/
Date date = new Date();
System.out.println(date);
/*
*获取该Date内部维护的long值
* 表示从1970-1-1 00:00:00着一刻
* 的毫秒值
*/
long time = date.getTime();
System.out.println(time);
/*
*让当前date表示给定毫秒所表示的时间
*/
date.setTime(time +24*60*60*1000);
System.out.println(date);
}
}
运行结果:
Wed Dec 23 11:23:24 CST 2020
1608693804488
Thu Dec 24 11:23:24 CST 2020
2.SimpleDateFormat——format方法
- 根据特定的日期格式,使得字符串和Date之间相互转换
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* SimpleDateFormat可以根据给定的日期格式字符串
* 使得可以在Date和String之间相互转换
*
*/
public class SimpelDateFormatDome {
public static void main(String[] args) {
//表示当前系统时间
Date date = new Date();
//输出Date默认的toString方法输出
System.out.println(date);
/*
希望输出格式是:2020/12/23 11:03
*/
String dateFormat =
"yyyy/MM/dd HH:mm:ss E a";
/*
*java.text.SimpleDateFormat
* 创建需要制订日期格式,该类会根据
* 给定的格式进行转换工作
*/
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
/*
*String.format(Date date)
* 将给定的Date按照SimpleDateFormat指定
* 的日期转换位字符串
*/
String str = sdf.format(date);
System.out.println(str);
}
}
运行结果:
Wed Dec 23 11:21:39 CST 2020
2020/12/23 11:21:39 周三 上午
Process finished with exit code 0
3.SimpleDateFormat——parse方法
4.常用字符串格式
4.DateFormat类
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 使用SimpleDateFormat的parse方法
* 将字符串转换为Date
*/
public class StringDateFormatDome2 {
public static void main(String[] args) throws ParseException {
String str = "2021-1-1 00:00:00";
String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format);
/*
*Date parse(String str)
* 将给定的字符串按simpleDateFormat指定
* 的日期格式并转换为Date对象返回
*/
Date date = sdf.parse(str);
System.out.println(date);
}
}
Fri Jan 01 00:00:00 CST 2021
练习:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
/**需求:
* 输入一个生日
* 计算度过了多少个日夜
*/
public class SimpleDateFormatDome3 {
public static void main(String[] args) throws ParseException {
/*
*思路:
* 1.将生日字符串转换为Date
* 2.创建一个Date表示系统时间(今天)
* 3.截取今天毫秒值
* 4.截取生日的毫秒值
* 5.用今天的毫秒值-生日的毫秒值
* 6.计算度过了多少毫秒 除以一天的毫秒值
* 7.输出度过了多少天
*/
System.out.println("请输入一个生日,格式(yyyy年MM月dd日):");
Scanner sc = new Scanner(System.in);
String sr = sc.next();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
Date d1 = sdf.parse(sr);
long d11 = d1.getTime();
//获取当前系统时间
Date d2 = new Date();
long d22 =d2.getTime();
long d33 = d22 - d11;
System.out.println(d33/(24*60*60*1000));
}
}
请输入一个生日,格式(yyyy年MM月dd日):
2000年1月1日
7662
calendar类
1.静态方法getInstance( )
2.getTime( )方法
import java.util.Calendar;
import java.util.Date;
/*
* 日历类
* 用于操作时间的类
*/
public class CalendarDome {
public static void main(String[] args) {
/*
* 默认创建的Calendar表示当前系统时间
*/
Calendar cal = Calendar.getInstance();
System.out.println(cal);
/*
* Date getTime()
* 该方法用于获取一个Date对象,该对象表示的时间
* 就是当前Calendar所表示的时间
*/
Date date = cal.getTime();
System.out.println(date);
}
}
java.util.GregorianCalendar[time=1608705019958,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=31,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2020,MONTH=11,WEEK_OF_YEAR=52,WEEK_OF_MONTH=4,DAY_OF_MONTH=23,DAY_OF_YEAR=358,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=2,HOUR_OF_DAY=14,MINUTE=30,SECOND=19,MILLISECOND=958,ZONE_OFFSET=28800000,DST_OFFSET=0]
Wed Dec 23 14:30:19 CST 2020
Process finished with exit code 0
3.setTime( )方法
import java.util.Calendar;
import java.util.Date;
/*
* Date 与 Calendar 的转换
*/
public class CalendarDome2 {
public static void main(String[] args) {
//已有一个Date对象
Date date = new Date();
/*
* 希望使用Calendar表示当前Date所表示的时间
*/
Calendar cal = Calendar.getInstance();
/*
* Calendar 提供一个方法
* void setTime(Date date)
* 该方法用于是使得当前Calendar表示给定的
* Date所表示的时间
*/
cal.setTime(date);
}
}
4.Calendar分量运行
设置时间
import java.util.Calendar;
import java.util.Date;
/**
* 使用Calendar设置时间
*
*/
public class CalendarDome3 {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
/*
* 希望表示2021-1-1 00:00:00
*/
cal.set(Calendar.YEAR,2021);
/*
*月份值可以使用常量
* 也可以直接给定值,需要注意:月份从0开始
* 既0表示1月
*/
cal.set(Calendar.MONTH,0);//月从0开始
/*
* Calendar.Date 与 Calendar.DAY_OF_MONTH
* 等价
*/
cal.set(Calendar.DAY_OF_MONTH,1);
cal.set(Calendar.HOUR_OF_DAY,0);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.SECOND,0);
Date date = cal.getTime();
System.out.println(date);
}
}
Fri Jan 01 00:00:00 CST 2021
Process finished with exit code 0
获取时间
import com.lagu.homwork2.CallServerInterface;
import java.util.Calendar;
/**
* 获取Calendar中某个时间分量对应的值
*/
public class CalendarDome4 {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
/*
* int get(int field)
* 根据给定的时间分量获取对应的值
*/
int year = cal.get(Calendar.YEAR);
int moon = cal.get(Calendar.MONTH)+1 ;
cal.set(Calendar.DAY_OF_MONTH,27);
int day = cal.get(Calendar.DAY_OF_MONTH);
int week = cal.get(Calendar.DAY_OF_WEEK)-1; //星期天是第一天
System.out.println(year +"-"+moon+"-"+day);
System.out.println("星期:"+ (week==0?7:week));
}
}
2020-12-27
星期:7
Process finished with exit code 0
使用Calendar计算时间
import java.util.Calendar;
import java.util.Date;
/**
* 使用Calendar计算时间
*/
public class CalendarDome5 {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
/*
*void add(int field,int n)
* 为当前Calendar指定时间分量上累加给定值
* 若传入负数,则是累减
*/
cal.add(Calendar.DAY_OF_YEAR,15);
Date date = cal.getTime();
System.out.println(date);
}
}
Thu Jan 07 16:54:47 CST 2021
Process finished with exit code 0
计算三个月后的10天后的那周的周三
import java.util.Calendar;
/**
* 计算三个月后的10天后的那周的周三
*/
public class CalendarDome6 {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH,3);
cal.add(Calendar.DAY_OF_YEAR,10);
cal.set(Calendar.DAY_OF_WEEK,4);
System.out.println(cal.getTime());
}
}
计算时间分量的最大值
import java.util.Calendar;
/**
* 计算时间分量的最大值
*/
public class CalendarDome7 {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
/*
*获取当月有多少天
*/
int days = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println(days);//31
}
}
输入一个日期,输出3年,3个月,3天后的当周的周三的日期
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
/**
* 输入一个日期,输出3年,3个月,3天后的当周的周三的日期
*/
public class CalendarDome8 {
public static void main(String[] args) throws ParseException {
/*
*1、输入日期:字符串转换为Date->Calendar
*2、加上三年三月三天
*3、确定当周是那周
*4、输出日期+4
*/
//输入日期字符串
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个日期:(格式:yyyy-MM-dd)");
String dateStr = scanner.next();
//字符串转换为日期
String format = "yyyy-MM-dd";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date dateInput = sdf.parse(dateStr);
System.out.println(dateInput);
//将Date转换为Calendar
Calendar cal = Calendar.getInstance();
cal.setTime(dateInput);
//计算时间
cal.add(Calendar.YEAR,3);
cal.add(Calendar.MONTH,3);
cal.add(Calendar.DAY_OF_MONTH,3);
cal.set(Calendar.DAY_OF_WEEK,4);
//将Calendar转换为Date
Date date = cal.getTime();
System.out.println(date);
//将Date转换为字符串
String str = sdf.format(date);
System.out.println(str);
}
}
请输入一个日期:(格式:yyyy-MM-dd)
2020-12-24
Thu Dec 24 00:00:00 CST 2020
Wed Mar 27 00:00:00 CST 2024
2024-03-27
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
/**
* 输入生产日期和保质期,输出
*/
public class ShelfLifeDome {
public static void main(String[] args) throws ParseException {
//1.创建Scanner
Scanner sc = new Scanner(System.in);
//2.接收生产日期
System.out.println("请输入生产日期:(格式yyyy-MM-dd)");
String produceDate = sc.next();
//3.接收保质期
System.out.println("请输入保质期:(天)");
int bzq = sc.nextInt();
//4.将字符串转换为Date
String format = "yyyy-MM-dd";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date date = sdf.parse(produceDate);
//5.将Date转换为Calendar
Calendar cal = Calendar.getInstance();
cal.setTime(date);
//加上保质期天数
cal.add(Calendar.DAY_OF_YEAR,bzq);
//减去14天
cal.add(Calendar.DAY_OF_YEAR,-14);
//设置为当周的周三
cal.set(Calendar.DAY_OF_WEEK,4);
//Calendar转换为Date
date = cal.getTime();
//将Date 转化为字符串
String str = sdf.format(date);
//输出
System.out.println(str);
}
}
集合框架
1.List和Set
2.集合的基本操作
集合保存元素的地址
举例:
1.先添加coll类
/**
* 作为集合元素进行测试的类
*
*/
public class Coll {
int x;
int y;
public Coll(int x,int y){
this.x = x;
this.y = y;
}
@Override
public String toString() {
return
"[" + "x=" + x +
", y=" + y + "]";
}
}
import java.util.ArrayList;
import java.util.Collection;
/**
*
*/
public class CollectionDome {
public static void main(String[] args) {
Collection c = new ArrayList();
Coll coll1 = new Coll(1,2);
Coll coll2 = new Coll(3,4);
c.add(coll1);
c.add(coll2);
System.out.println(c);
coll1.x = 2;
System.out.println(c);
}
}
查看集合是否包含给定元素
import java.util.Objects;
/**
* 作为集合元素进行测试的类
*
*/
public class Coll {
int x;
int y;
public Coll(int x,int y){
this.x = x;
this.y = y;
}
@Override
public String toString() {
return
"[" + "x=" + x +
", y=" + y + "]";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Coll coll = (Coll) o;
return x == coll.x &&
y == coll.y;
}
}
/**
* 查看集合是否包含给定元素
*/
public class CollectionDome2 {
public static void main(String[] args) {
Collection c = new ArrayList();
Coll coll1 = new Coll(1,2);
Coll coll2 = new Coll(2,3);
Coll coll3 = new Coll(3,4);
c.add(coll1);
c.add(coll2);
c.add(coll3);
Coll coll4 = new Coll(3,4);
System.out.println(coll3.equals(coll4)); //false 是因为 没有重写equals ,默认是 判断是否为同一个对象。但是不是同一个对象
/**
* boolean contains(Object o)
* 查看当前集合是否包含给定的元素o
*
*包含取决于集合的元素是否与有给定元素
* equals比较为true的。
*/
if(c.contains(coll4)){
System.out.println("包含");
}else {
System.out.println("不包含");
}
}
}
true
包含
Process finished with exit code 0
集合的其它方法
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
/**
* 集合的其它方法
*/
public class CollectionDome3 {
public static void main(String[] args) {
Collection c = new ArrayList();
/*
*int size()
*获取集合元素个数
*/
int s = c.size();
System.out.println(s);
/*
*boolean isEmpty()
*查看集合是否不包含任何元素
*/
boolean e = c.isEmpty();
System.out.println("不含元素:" + e);
c.add("1");
c.add(new Date());
System.out.println(c.size());
System.out.println("不含元素:" + c.isEmpty());
/*
*清空元素
*/
c.clear();
System.out.println(c.size());
System.out.println("不含元素:" + c.isEmpty());
}
}
0
不含元素:true
2
不含元素:false
0
不含元素:true
2.addAll、ContainsAll
集合的批量处理方法
import java.util.ArrayList;
import java.util.Collection;
/**
* 集合的批量处理方法
*/
public class CollectionDome1 {
public static void main(String[] args) {
Collection c1 = new ArrayList();
c1.add("java");
c1.add(".net");
c1.add("c#");
c1.add("php");
System.out.println(c1);
Collection c2 = new ArrayList();
c2.add("android");
c2.add("ios");
/*
* boolean addAll(Collection c)
* 将给定的集合中的所有元素添加到当前集合中
* 当调用该方法后当前元素数列发生了变化
* 则返回true
*/
c1.addAll(c2);
System.out.println(c1);
}
}
[java, .net, c#, php]
[java, .net, c#, php, android, ios]
3.删除元素
import com.lagu.homwork2.com.danei.SE01.day03.Coll;
import java.util.ArrayList;
import java.util.Collection;
/**
* 删除元素
*/
public class CollectionDome2 {
public static void main(String[] args) {
Collection c = new ArrayList();
c.add(new Coll(1,2));
c.add(new Coll(2,3));
c.add(new Coll(1,2));
Coll cell = new Coll(1,2);
System.out.println(c);
/*
* boolean remove(Object o)
* 从当前集合中删除给定元素的第一个equals比较
* 为true的
* 删除元素是根据元素的equals的结果判断的
*/
c.remove(cell);
System.out.println(c);
}
}
[[x=1, y=2], [x=2, y=3], [x=1, y=2]]
[[x=2, y=3], [x=1, y=2]]
Process finished with exit code 0
4.迭代器–用来遍历集合
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
* 迭代器用来遍历集合
*/
public class IteratorDome {
public static void main(String[] args) {
Collection c = new ArrayList();
c.add("a");
c.add("b");
c.add("c");
c.add("d");
c.add("e");
/*
*Iterator是一个接口
* java希望我们使用统一的方式遍历所有集合
* 使用迭代器遍历集合必须遵循以下过程:
* 问,取,删(删除不是必须的操作)
*/
Iterator it = c.iterator();
/*
*boolean hasNext();
*询问迭代器,遍历的集合是否还有元素可以取出
*/
while (it.hasNext()){
Object o = it.next();
String str = (String)o;
System.out.println(str);
}
}
}
a
b
c
d
e
Process finished with exit code 0
遍历删除某些元素
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
* 遍历删除某些元素
* 想要it.remove() 先要 it.next() 取出元素,想要取出元素 先要 it.hasNext()判断有么有
*/
public class IteratorDome2 {
public static void main(String[] args) {
Collection c = new ArrayList();
c.add("one");
c.add("#");
c.add("two");
c.add("#");
c.add("three");
c.add("#");
c.add(null);
c.add("four");
System.out.println(c);
Iterator it = c.iterator();
while (it.hasNext()){
/*
*it.next 取出元素
*/
String str = (String)it.next();
// if(str.equals("#")){ //error “null不能.” 集合可以存在空 ,会造成异常
/*
* 尽量使用字面量.equals(变量)
* 这样可以避免空指针异常的产生
*/
if("#".equals(str)){
/*
* 在使用迭代器遍历集合的过程中
* 不可以通过集合的相关方法改变
* 集合元素
*/
// c.remove(str); error
/*
*迭代器的remove方法用来从集合中
* 删除刚刚next()出来的元素
*/
it.remove();
}
}
System.out.println(c);
}
}
5.增强型for循环
新循环只能用来遍历集合
import java.util.ArrayList;
import java.util.Collection;
/**
* 新循环,又名:增强for循环,for each
* 从java 1.5(5.0)后退出的新特性
* 新循环不能代替传统循环的工作,
* 新循环只能用来遍历集合或数组
*/
public class NewForDome {
public static void main(String[] args) {
Collection c = new ArrayList();
c.add("one");
c.add("two");
c.add("#");
c.add("three");
c.add("four");
/*
* for(Object o : c){}
* 等价于:
* Iterator it = c.iterator();
* while(it.hasNext){
* Object o = it.next();
* }
*/
/*
*新循环并非新的语法,之上编译器在编译成
* class文件时,新循环转换为了迭代器
* 所以,在新循环遍历集合时,不能通过
* 集合的方法来改集合元素
*/
for(Object o : c){
String str = (String) o;
System.out.println(str);
}
// 左边是类型 变量,集合默认都是Object 类型 ,右边是要接收的集合或数组名
}
}
one
two
#
three
four
Process finished with exit code 0
在这里插入代码片
新循环遍历数组
/**
* 新循环遍历数组
*/
public class NewForDome2 {
public static void main(String[] args) {
String[] array = {"1","2","3","4","5"};
for(int i=0;i<array.length;i++){
System.out.print(array[i] + " ");
}
for(String str:array){
System.out.print(str + " ");
}
}
}
/**
* 新循环遍历数组
*/
public class NewForDome2 {
public static void main(String[] args) {
String[] array = {"1","2","3","4","5"};
for(int i=0;i<array.length;i++){
System.out.print(array[i] + " ");
}
System.out.println();
for(String str:array){
System.out.print(str + " ");
}
}
}
1 2 3 4 5
1 2 3 4 5
Process finished with exit code 0
泛型机制
1.泛型机制简介
public class TypeDome<T> {
private T x;
public TypeDome(T x){
this.x = x;
}
public T getX() {
return x;
}
public void setX(T x) {
this.x = x;
}
@Override
public String toString() {
return
"x=" + x ;
}
}
public class TestTypeDome {
public static void main(String[] args) {
TypeDome<String> t = new TypeDome<String>("1");
System.out.println(t.toString());
TypeDome<Integer> i = new TypeDome<>(1);
System.out.println(t.toString());
}
}
x=1
x=1
Process finished with exit code 0
2.java泛型在集合中的运用
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
* 所有的集合都支持泛型
* 而集合中 泛型用来定义定义的元素类型
*/
public class CollectionDome3 {
public static void main(String[] args) {
Collection<String> c = new ArrayList<String>();
c.add("one");
c.add("two");
c.add("three");
c.add("four");
for(Object o: c){
System.out.println(o);
}
Iterator<String> it = c.iterator();
while (it.hasNext()){
String str = it.next();
System.out.println(str);
}
}
}
one
two
three
four
one
two
three
four
Process finished with exit code 0
List
1.ArrayList 和 LinkedList
ArrayList 更适合查找,而LinkedList更适合插入和删除
2. get 和 set方法
这些都是List独有的方法
List 集合获取和替换元素
import java.util.ArrayList;
import java.util.List;
/**
* List 集合,通常是有序集
* 特点是库根据下标操作元素
*/
public class ListDome {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("one");
list.add("two");
list.add("three");
list.add("four");
/*
* T get(int index)
* 获取给定下标所对应的元素
*/
String str = list.get(2);
System.out.println(str);
/*
* List集合可以通过以下标遍历集合每个元素
*/
for(int i=0;i<list.size();i++){
str = list.get(i);
System.out.println(str);
}
/*
* T set(int index,T t)
* 将给定的元素设置的位置上
* 返回值为原位置上的元素
* 所以该方法是替换元素操作
*/
System.out.println(list);
String old = list.set(1,"2");
System.out.println(list);
System.out.println("被替换的元素:" + old);
}
}
three
one
two
three
four
[one, two, three, four]
[one, 2, three, four]
被替换的元素:two
Process finished with exit code 0
List集合的方法插入与删除
import java.util.ArrayList;
import java.util.List;
/**
* List集合的方法
* 插入与删除
*/
public class ListDome2 {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
/*
* void add(int index,T t)
* 将给定的元素添加到给定的位置上
* 原位置及后续元素顺序向后移动
* 插入操作。
*/
System.out.println(list);
list.add(1,"2");
System.out.println(list);
/*
* E remove(int index)
* 删除给定位置上的元素
* 返回值为被删除的元素
*/
String remove = list.remove(2);
System.out.println(list);
System.out.println("被删除的是:" + remove);
}
}
[one, two, three]
[one, 2, two, three]
[one, 2, three]
two
Process finished with exit code 0
3.subList方法
List的方法获取子集
import java.util.ArrayList;
import java.util.List;
/**
* List的方法
* 获取子集
*/
public class ListDome3 {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
list.add(i);
}
System.out.println(list);
/*
* List subList(int Start,int end)
* 获取当前结合中的子集
*/
List<Integer> subList = list.subList(3, 8);
System.out.println(subList);
/*
* 将子集的元素扩大10倍
*/
for(int i=0;i<subList.size();i++){
int num = subList.get(i);
num *=10;
subList.set(i,num);
}
System.out.println(subList);
/*
* 修改子集元素,会影响原集合
*/
System.out.println(list);
}
}
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[3, 4, 5, 6, 7]
[30, 40, 50, 60, 70]
[0, 1, 2, 30, 40, 50, 60, 70, 8, 9]
Process finished with exit code 0
4.List转换为数组
集合转为数组
import java.util.ArrayList;
import java.util.Collection;
/**
* 集合转换为数组
* Collection 中定义了两个方法
* Object[] toArray[]
* <T>T[] toArray(T[] array)
*/
public class ToArrayDome {
public static void main(String[] args) {
Collection<String> c = new ArrayList<String>();
c.add("one");
c.add("two");
c.add("three");
// Object[] array = c.toArray();
/*
* 传入的数组长度有区别
* 若给定的数组长度不足以保存集合中所有元素
* 集合子集创建一个同类型数组
* 若长度够长,则使用我们给定的数组
*/
String[] array = c.toArray(new String[10]);
System.out.println(array); //返回的是地址
for(String str:array){
System.out.println(str);
}
}
}
one
two
three
null
null
null
null
null
null
null
Process finished with exit code 0
数组转换为List集合
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 数组转换为List集合
* 不能转换为Set集合,原因在于set集合不能存放重复元素
*/
public class ToListDome {
public static void main(String[] args) {
String[] array = {"1","2","3","4","5"};
/*
*通过Arrays转换的集合是不能添加新元素的
*/
List<String> list = Arrays.asList(array);
System.out.println(list);
/*
*所有的集合(包括Set集合)都支持一个构造方法,
* 参数传入一个Collection这个构造方法的好处是,
* 在创建当前集合时默认就包含给定集合中的所有
* 元素
*/
List<String> list1 = new ArrayList<String>(list);
list1.add("6");
System.out.println(list1);
}
}
6.Conllections.sort方法
import java.util.*;
/**
* 集合排序
*/
public class SortCollection {
public static void main(String[] args) {
List<Integer> c = new ArrayList<>();
Random random = new Random();
for (int i=0;i<10;i++){
c.add(random.nextInt(100));
}
System.out.println(c);
/*
*通过Collections 这个集合的工具类
*我们可以对List集合进行自然排序
*/
Collections.sort(c);
System.out.println(c);
}
}
[64, 23, 74, 68, 76, 16, 8, 48, 95, 12]
[8, 12, 16, 23, 48, 64, 68, 74, 76, 95]
Process finished with exit code 0
import com.lagou.task10.StaticOuter;
import com.lagu.homwork2.com.danei.SE01.day03.Coll;
import com.lagu.homwork2.com.danei.review.taks1.Cell;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Comparable接口
*/
public class SortCollection2 {
public static void main(String[] args) {
List<Coll> list = new ArrayList<Coll>();
list.add(new Coll(4,5));
list.add(new Coll(1,7));
list.add(new Coll(1,2));
list.add(new Coll(3,3));
System.out.println(list);
/*
* 使用Collections的sort方法进行排序的集合,
* 要求元素必须实现Comparable接口
* 只有实现了该接口才认为是可比较的元素
*/
Collections.sort(list);
System.out.println(list);
}
}
6.Comparable接口
package com.lagu.homwork2.com.danei.SE01.day03;
import java.util.Objects;
/**
* 作为集合元素进行测试的类
*
*/
public class Coll implements Comparable<Coll>{
int x;
int y;
public Coll(int x,int y){
this.x = x;
this.y = y;
}
@Override
public String toString() {
return
"[" + "x=" + x +
", y=" + y + "]";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Coll coll = (Coll) o;
return x == coll.x &&
y == coll.y;
}
/*
* 返回值不关注具体的值,值关注取值范围
* 返回值<0:当前对象比给定的对象小
* 返回值=0:当前对象相当
* 返回值>0: 当前对象比给定的对象大
*/
@Override
public int compareTo(Coll o) {
/*
* 比较规则如下
* y值大就大
*/
return this.y - o.y;
}
}
重新定义比较器
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class sortCollection3 {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("张三");
list.add("boss");
list.add("王麻子");
list.add("德玛西亚");
list.add("嘉文");
System.out.println(list);
Comparator<String> com = new MyComparator();
Collections.sort(list,com);
System.out.println(list);
}
}
/**
*何时应该声明比较器
* 当集合中的元素已经实现了Comparable接口,并且实现了
* 比较规则,但是该比较规则不能满足我们对于排序的需求时
* 我们可以额外定义一个比较规则
*/
class MyComparator implements Comparator<String> {
/*
*自定义比较字符串的规则,字符串多的大
*/
public int compare(String o1,String o2) {
return o1.length() - o2.length();
}
}
[张三, boss, 王麻子, 德玛西亚, 嘉文]
[张三, 嘉文, 王麻子, boss, 德玛西亚]
Process finished with exit code 0
/**
* 创建集合实现 工资从小打大排序
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class A001 {
public static void main(String[] args) {
List<Emp> e = new ArrayList<Emp>();
e.add(new Emp("Terry",27,9000));
e.add(new Emp("Allen",25,8000));
e.add(new Emp("Smith",24,6500));
System.out.println(e);
/*
* 何时使用匿名内部类:
* 当我们需要用到一个实例,而该实例所属的类
* 需要实现一个接口或者继承一个类,并且该实例
* 仅在这里用一次,不会在其它地方使用时,我们
* 就应该选取使用匿名内部类的形式创建实例。
*/
Comparator<Emp> com = new Comparator<Emp>(){ //Comparator 接口
@Override
public int compare(Emp o1, Emp o2) {
return (int)(o1.salary - o2.salary);
}
};
Collections.sort(e,com);
System.out.println(e);
}
}
class Emp{
String name;
int age;
double salary;
public Emp() {
}
public Emp(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
@Override
public String toString() {
return name + " ," + age + " ," + salary;
}
}
[Terry ,27 ,9000.0, Allen ,25 ,8000.0, Smith ,24 ,6500.0]
[Smith ,24 ,6500.0, Allen ,25 ,8000.0, Terry ,27 ,9000.0]
Process finished with exit code 0
队列和栈
1.队列的定义
游戏排队
2.队列的基本应用
队列基本应用
import java.util.LinkedList;
import java.util.Queue;
/**
* 队列
* 保存一组数组,在存取元素必须遵循先进先出原则
* FIFO(First Input First Output)
*/
public class QueueDome {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<String>();
/**
* boolean offer(T t)
* 入队方法
* 将给定元素添加到队列队尾。添加成功返回true
*/
queue.offer("A");
queue.offer("B");
queue.offer("C");
queue.offer("D");
System.out.println(queue); //[A, B, C, D]
/*
* T poll()
* 用于获取队首元素,出队操作
* 获取后,队列中将不再包含该元素
*/
String str = queue.poll();
System.out.println(str); //A
System.out.println(queue);//[B, C, D]
/*
* T peek()
* 用于获取队首元素,仅应用,不做出队操作
*/
str = queue.peek();
System.out.println(str);
System.out.println(queue); //[B, C, D]
/*
* 遍历队列是一次性的
*/
while (queue.size()>0){
str = queue.poll();
System.out.print(str + " "); //B C D
}
System.out.println(queue);//[]
}
}
3.双端队列
4.栈的基本操作
用处:文件系统
import java.util.Deque;
import java.util.LinkedList;
/**
* 栈
* 用于存储一组数据,存在元素必须遵循先进后出原则
* 通常用于记录一组操作可追溯
*/
public class StatckDome {
public static void main(String[] args) {
Deque<String> stack = new LinkedList<String>();
/*
*void push(T t)
* 向栈顶“压入”一个元素
* 入栈操作
*/
stack.push("A");
stack.push("B");
stack.push("C");
stack.push("D");
System.out.println(stack); //[D, C, B, A]
/*
*T pop()
* 取出栈顶元素,出栈操作
* 取出后,该元素会从栈中删除
*/
String str = stack.pop();
System.out.println(str); // D
System.out.println(stack);//[C, B, A]
str = stack.peek();
System.out.println(str); //C
System.out.println(stack);//[C, B, A]
/*
* 同样的,遍历栈也是一次性的
*/
while (stack.size()>0){
str = stack.pop();
System.out.print(str + " ");//C B A
}
System.out.println(stack);//[]
}
}
Map集合
1.Map集合常用方法
import java.util.HashMap;
import java.util.Map;
/**
* Map
* 该数据结构看起来更像是一个多行两列的表格
* 每个数据中包含两个信息Key-value
* 其中Key在Map中不允许重复,重复指的是equals为true
*
*/
public class MapDome {
public static void main(String[] args) {
/*
*创建一个Map
* key是字符串,value是整数
*/
Map<String,Integer> map = new HashMap<String,Integer>();
/*
* V put(K k,V v)
* 将给定的Key与对应的value存入Map中
* 若key在Map中不存在,则添加新内容
* 那么返回值就是null
* 若给定的Key在Map中已存在,则是替换value操作
* 那么返回的是被替换的value值
*/
System.out.println(map);//{}
map.put("数学",115);
map.put("语文",110);
map.put("英语",110);
map.put("物理",100);
map.put("化学",95);
map.put("生物",99);
map.put("体育",90);
map.put("体育",98);
System.out.println(map);//{物理=100, 生物=99, 体育=98, 数学=115, 化学=95, 语文=110, 英语=110}
/*
* V get(K k)
* 根据给定的key获取对应的value
*/
Integer num = map.get("英语");
System.out.println("英语:" + num);//英语:110
/*
* 给定一个Map中不存在的key返回值则为null
*/
Integer num2 = map.get("高数");//注意是Integer
System.out.println("高数:" + num2); //高数:null
/*
* boolean containsKey(K k)
* 判断当前Map中是否包含给定的Key
* 是否有根据Key的equals判断的
*/
if(map.containsKey("数学")){//包含数学
System.out.println("包含数学");
}else{
System.out.println("不包含数学");
}
/*
* V remove(K k)
* 根据给定的Key删除这一项
* 返回值为删除的value
* 若没有找到对应的Key,则返回值为null
*/
System.out.println(map);//{物理=100, 生物=99, 体育=98, 数学=115, 化学=95, 语文=110, 英语=110}
Integer remove = map.remove("化学");
System.out.println(map);//{物理=100, 生物=99, 体育=98, 数学=115, 语文=110, 英语=110}
System.out.println(remove);
}
}
2.HashMap的原理
用处:适合大量数据查找
3.HashMap的应用
4.hashCode方法
import java.util.Objects;
/**
* 重写equalse方法时应当重写hashCode方法
* 重写规则如下:
* 若两个对象equals方法比较结果为true,那么hashcode
* 返回的数字必须相同
* 若equals方法比较结果为false,他们的hashCode方法
* 返回值应该尽量不同,否则影响HashMap性能
* hashCode方法在当前对象内容没有发生改变的前提下多次
* 调用应当返回相同的数字。
*/
public class Point {
private int x;
private int y;
public Point() {
}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Point point = (Point) o;
return x == point.x &&
y == point.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
hashCode队Map操作的影响
import java.util.HashMap;
import java.util.Map;
/**
* hashCode队Map操作的影响
*/
public class MapDome2 {
public static void main(String[] args) {
Map<Point,Integer> map = new HashMap<Point,Integer>();
Point p = new Point(1,2);
map.put(p,100);
boolean contains = map.containsKey(p);
System.out.println("包含Key" + contains);//包含Keytrue
System.out.println(map);//day05.Point@3e2=100
Integer i = map.get(p);
System.out.println(i);//100
System.out.println(p.hashCode());//994
//内容变化了,hashCode值就会变化
p.setX(2);
System.out.println(p.hashCode());//1025
i = map.get(p);
System.out.println(i);//根据新的hashCode查找 null
System.out.println(p.getX());//2
contains = map.containsKey(p);// 找不到Map
System.out.println("包含p:" + contains);//false
System.out.println(map);//day05.Point@401=100
System.out.println(p.getX());//2
map.put(p,200);
System.out.println(map);//Point@401=200,Point@401=100
map.remove(p);//删除 Point@401=200
System.out.println(map);//Point@401=100
p.setX(1);
Integer ii = map.remove(p);
System.out.println("删除的是:" + ii);
System.out.println(map);
/*
*使用HashMap时应该注意:
* 作为Key的对象有以下要求:
* 1:首先Key这个类重写了equals方法,那么重写hashCode的要求必须满足
* 2:作为Key的对象若存入HashMap后,其会影响HashCode值的内容不要发生改变,
* 否则可能会影响Map的操作
*/
}
}
5.HashMap性能调优
Map<Point,Integer> map = new HashMap<Point,Integer>(10000); // 3/4 初始16
Map的遍历
1.Map的遍历
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* 遍历Map的三种方式
* 1:遍历所有的key
* 2: 遍历所有的键值对(Key-value)
* 3:遍历所有的value(不常用)
*/
public class MapDome3 {
public static void main(String[] args) {
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("数学",115);
map.put("语文",110);
map.put("英语",110);
map.put("物理",100);
map.put("化学",95);
map.put("生物",99);
map.put("体育",90);
map.put("体育",98);
/*
* 遍历所有的key
* Set><K> KeySet()
* 该方法可以获取Map中所有的key,并将它们存入
* 一个Set集合中返回
* 所以,遍历该集合就等于遍历了所有的Key了
*/
Set<String> keySet = map.keySet();
for (String key: keySet){
System.out.println("key: " + key);
}
/*
* 遍历键值对
* Set<Entry> entrySet()
* 该方法会将每一组key-value存入一个Entry实例中,并将这些
* Entry实例存入一个Set集合并返回
* 我们只需要遍历该集合,拿到每个Entry实例
* 并获取其中的key和value即可
*/
Set<Map.Entry<String,Integer>> entrySet = map.entrySet();
for(Map.Entry<String,Integer> e :entrySet){
String key = e.getKey();
Integer value = e.getValue();
System.out.println(key + ": " + value);
}
/*
* 遍历所有的value
*/
Collection<Integer> values = map.values();
for (Integer value: values){
System.out.println(value);
}
}
}
key: 物理
key: 生物
key: 体育
key: 数学
key: 化学
key: 语文
key: 英语
物理: 100
生物: 99
体育: 98
数学: 115
化学: 95
语文: 110
英语: 110
100
99
98
115
95
110
110
2.Map常用应用场合
文件操作-file(新纪元)
查看文件周边信息
import java.io.File;
/**
* java.io.File
*/
public class FileDome {
public static void main(String[] args) {
/*
*用相对路径,相对当前项目的根目录 用 "."表示
*
* File.separator表示不同系统的目录层级分隔符
* 为了忽略平台差异性,我们在写路径时应当使用
* 该常量
* 在windows表示 \\
* 在linux表示//
*/
File file =
new File("."+File.separator +"Dome.txt");
/*
* String getNane()
* 获取File表示的文件或者目录名字
*/
String fileName = file.getName();
System.out.println(fileName);
/*
* boolean exists()
* 判断当前File所表示的文件或目录是否真实
* 存在
*/
boolean exists = file.exists();
System.out.println("是否真实存在:" + exists);
/*
* 创建文件不存在才可以创建
*/
/*
* long length()
* 获取当前File所表示的文件所占用的字节量
*/
long length = file.length();
System.out.println("大小:" + length + "字节");
/*
* 查看当前File表示表示的文件是否具有可读,可写,可运行的权限
*/
file.canRead();
file.canWrite();
file.canExecute();
/*
*获取当前文件或目录的最后修改时间
*/
long time = file.lastModified();
/*
* boolean isFile()
* 判断当前File对象表示的是否为一个文件
*/
boolean isFile = file.isFile();
System.out.println("是文件:" + isFile);
}
}
创建一个空文件
import java.io.File;
import java.io.IOException;
/**
* 使用File操作文件
* 创建一个空文件
*/
public class FileDome2 {
public static void main(String[] args) throws IOException {
/*
*当前项目的根目录下创建一个文件
* test.txt
*/
// 表示当前目录,可以忽略 "./"
File file = new File("test.txt");
if(!file.exists()){
file.createNewFile();
System.out.println("文件创建成功");
}
}
}
删除一个文件
import java.io.File;
/**
* 删除一个文件
*/
public class FileDome3 {
public static void main(String[] args) {
/*
*删除当前目录下的test.txt文件
*/
File file = new File("test.txt");
if(file.exists()){
file.delete();
System.out.println("删除成功");
}
}
}
使用File创建一个目录
import java.io.File;
/**
* 使用File创建一个目录
*/
public class FileDome4 {
public static void main(String[] args) {
/*
* 在当前目录下创建一个目录dome
*/
File dir = new File("dome");
if(!dir.exists()){
dir.mkdir();
System.out.println("创建目录成功");
}
}
}
删除一个目录
import java.io.File;
/**
* 删除一个目录
*/
public class FileDome5 {
public static void main(String[] args) {
/*
* 删除当前目录下的目录dome
*/
File dir = new File("dome");
boolean isDir = dir.isDirectory();
System.out.println("是否为目录:" + isDir);
if(dir.exists()){
dir.delete();
System.out.println("删除目录成功");
}
}
}
创建多级目录
import java.io.File;
/**
* 创建多级目录
*/
public class FileDome6 {
public static void main(String[] args) {
/*
* 当前目录下创建
* a\b\c\d\e\f\g\h\i\j\k
*/
File dir = new File("a\\b\\c\\d\\e\\f\\g\\h\\i\\j\\k");
if(!dir.exists()){
/*
*mkdirs 方法在创建当前目录时,会自动
* 创建所有不存在的父目录
*/
dir.mkdirs();
System.out.println("创建目录成功");
}
}
}