访问级别 | 访问修饰符 | 同类 | 同包 | 子类 | 不同包 |
---|---|---|---|---|---|
公开 | public | ✅ | ✅ | ✅ | ✅ |
受保护 | protected | ✅ | ✅ | ✅ | ❌ |
默认 | 无 | ✅ | ✅ | ❌ | ❌ |
私有 | private | ✅ | ❌ | ❌ | ❌ |
public class ExtendDemo {
public static void main(String[] args) {
Zi zi = new Zi();
zi.show();
}
}
class Fu{
int num = 10;
int numFu = 100;
public void method(){
System.out.println("父类method");
}
}
class Zi extends Fu{
int num = 20;
int numZi = 200;
public void method(){
System.out.println("子类method");
}
public void show(){
int num = 30;
System.out.println("局部变量num:"+num);// 30
System.out.println("本类成员变量num:"+this.num);// 20
System.out.println("父类成员变量num:"+super.num);// 10
// 访问本类的method方法
this.method();// 子类method
// 访问父类的method方法
super.method();// 父类method
}
}
//局部变量num:30
//本类成员变量num:20
//父类成员变量num:10
//子类method
//父类method
类在继承时,先创建父类空间,然后再创建子类空间
这张图执行顺序:
* 先在方法区加载类的信息,方法区为类中的方法分配空间和地址。
* 然后main方法进栈,然后new对象,先创建父类空间,再创建子类空间,并为其变量分配空间
值得注意的是,父类和子类重名的变量和方法没有被覆盖,而是独自存在。
new子类对象,想访问父类的重名的public变量和方法,通过super.的方式访问
图中未画出给Object类分配的空间
多态成员变量:编译运行看左边
Fu f=new Zi();
System.out.println(f.num);//f是Fu中的值,只能取到父中的值
多态成员方法:编译看左边,运行看右边
这里主要由于方法的动态绑定机制
Fu f1=new Zi();
3.属性没有重写之说,属性编译的时候看类型
System.out.println(f1.show());//f1的门面类型是Fu,但实际类型是Zi,所以调用的是重写后的方法。
使用格式:父类类型 变量名=new 子类类型();
适用场景:当不需要面对子类类型时,通过提高扩展性,或者使用父类的功能就能完成相应的操作。
使用格式:子类类型 变量名=(子类类型) 父类类型的变量;
适用场景:当要使用子类特有功能时。
package day0524;
public class demo04 {
public static void main(String[] args) {
People p=new Stu();
p.eat();
//调用特有的方法
Stu s=(Stu)p;
s.study();
//((Stu) p).study();
}
}
class People{
public void eat(){
System.out.println("吃饭");
}
}
class Stu extends People{
@Override
public void eat(){
System.out.println("吃水煮肉片");
}
public void study(){
System.out.println("好好学习");
}
}
class Teachers extends People{
@Override
public void eat(){
System.out.println("吃樱桃");
}
public void teach(){
System.out.println("认真授课");
}
}
public class duotai {
public static void main(String[] args) {
//因为aa实际上还是BB类型的,现在只是属性和类型限定为AA,运行时还有BB的特征
AA aa = new BB();
System.out.println(aa instanceof AA);//true
System.out.println(aa instanceof BB);//true
}
}
class AA{
}
class BB extends AA{
}
子类的方法的形参列表,方法名称,要和父类方法的形参列表,方法名称完全一样
子类方法的返回类型和父类方法返回类型一样,或者是父类返回类型的子类 返回相等或从小原则
子类方法大于等于父类方法的访问权限
==
a 既可以判断基本类型,又可以判断引用类型
b 如果判断基本类型,判断的是值是否相等
c 如果判断引用类型,判断的是地址是否相等,即判定是不是同一个对象
public void test01(){
int[] a = new int[10];
int[] b = a;
System.out.println(a == b);//true
//String类节省内存的方法
String c = "abc";
String d = "abc";
System.out.println(c == d);//true 常量区的特性
int[] e = new int[10];
int[] f = new int[10];
System.out.println(e == f);//false
}
equals
a.equals:是Object类中的方法,只能判断引用类型
b.默认判断的是地址是否相等,子类中**往往重写该方法**,用于判断内容是否相等
public void test02(){
//equals
String a = "abc";
String b = "abc";
String c = "abcd";
System.out.println(a.equals(b));//true
System.out.println(a.equals(c));//false
int e = 10;
int f = 10;
//e.equals(f) xxx
}
hashcode
a.提高具有哈希结构的容器的效率
b.两个引用,如果指向的是同一个对象,则哈希值肯定是一样的
c.两个引用,如果指向的是不同对象,则哈希值是不一样的
d.哈希值主要根据地址号来的,不能完全将哈希值等价子地址
e.后面在集合中hashCode 如果需要的话,也会重写
f.两个对象的hashCode相同,并不一定表示两个对象就相同,也就是不一定适用于equals(java.lang.Object) 方法,只能够说明这两个对象在散列存储结构中,如Hashtable,他们**“存放在同一个篮子里”**。
public class HashTest {
private int i;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public int hashCode() {
return i % 10;
}
public final static void main(String[] args) {
HashTest a = new HashTest();
HashTest b = new HashTest();
a.setI(1);
b.setI(1);
Set<HashTest> set = new HashSet<HashTest>();
set.add(a);
set.add(b);
System.out.println(a.hashCode() == b.hashCode());//true
System.out.println(a.equals(b));//flase
System.out.println(set);//[oopBase.HashTest@1, oopBase.HashTest@1]
}
}
public void test03(){
//hashcode
int a[] = new int[10];
int b[] = new int[10];
int c[] = a;
System.out.println(a);//[I@5e5d171f
System.out.println(b);//[I@24313fcc
System.out.println(c);//[I@5e5d171f
System.out.println(a.hashCode() == b.hashCode());//true
System.out.println(a.hashCode() == c.hashCode());//false
}
tostring
a.默认返回:全类名+@+哈希值的十六进制
b.子类往往重写to String方法,用于返回对象的属性信息
c.重写toString方法,打印对象或拼接对象时,都会自动调用该对象的toString形式
d.当直接输出一个对象时,toString 方法会被默认的调用
public void test04(){
//toString
String a = "abc";
int[] b = new int[10];
System.out.println(a.toString());//abc
System.out.println(b.toString());//[I@24313fcc
}
finalize
a.当对象被回收时,系统自动调用该对象的finalize方法。子类可以重写该方法,做一些释放资源的操作
b.什么时候被回收:当**某个对象没有任何引用时,**则jvm就认为这个对象是一个垃圾对象,就会使用垃圾回收机制来销毁该对象,在销毁 该对象前,会先调用finalize方法
c.垃圾回收机制的调用,是由系统来決定(即有自己的GC算法),也可以通过System.gc() 主动触发垃圾回收机制
public class Test {
public static void main(String[] args) {
GirlFriend1 girlFriend1 = GirlFriend1.getGirlFriend();
System.out.println(girlFriend1.getName());
GirlFriend2 girlFriend2 = GirlFriend2.getInstance();
System.out.println(girlFriend2.getName());
}
}
//饿汉式
class GirlFriend1{
private String name;
private GirlFriend1(){
this.name = "小冰";
}
public String getName(){
return this.name;
}
public static GirlFriend1 girlFriend1 = new GirlFriend1();
public static GirlFriend1 getGirlFriend(){return girlFriend1;}
}
//懒汉式
class GirlFriend2{
private String name;
private static GirlFriend2 girlFriend2 = null;//
private GirlFriend2(){
this.name = "小娜";
}
public String getName(){
return this.name;
}
public static GirlFriend2 getInstance(){
if(girlFriend2 == null){
return new GirlFriend2();
}
return girlFriend2;
}
}
public class Test {
public static void main(String[] args) {
A a = new A();
B b = new B();
a.cal();
b.cal();
}
}
abstract class Template{
public abstract void job();
public void cal(){
long start = System.currentTimeMillis();
job();
long end = System.currentTimeMillis();
System.out.println("时间" + (end - start));
}
}
class A extends Template{
@Override
public void job() {
long num = 0;
for (long i = 0; i < 100000000; i++) {
num += i;
}
}
}
class B extends Template{
@Override
public void job() {
long num = 0;
for (long i = 0; i < 100000000; i++) {
num *= i;
}
}
}
//接口也相当于一个类但是不能实例化
//接口比抽象类更能提供一般的方法
public class Test2 {
public static void main(String[] args) {
USB[] usbs = new USB[2];//引用数组
usbs[0] = new Phone();
usbs[1] = new Camera();
for (int i = 0; i < usbs.length; i++) {
usbs[i].work();
if(usbs[i] instanceof Phone){
((Phone)usbs[i]).cal();
}
}
}
}
class Phone implements USB{
@Override
public void work() {
System.out.println("手机使用中");
}
public void cal(){
System.out.println("手机可以打电话");
}
}
class Camera implements USB{
@Override
public void work() {
System.out.println("相机使用中");
}
public void cal(){
System.out.println("相机可以照相");
}
}
package com.atguigu.java;
public class StaticProxyTest {
public static void main(String[] args) {
Star s = new Proxy(new RealStar());
s.confer();
s.signContract();
s.bookTicket();
s.sing();
s.collectMoney();
}
}
interface Star {
void confer();// 面谈
void signContract();// 签合同
void bookTicket();// 订票
void sing();// 唱歌
void collectMoney();// 收钱
}
class RealStar implements Star {
public void confer() {
}
public void signContract() {
}
public void bookTicket() {
}
public void sing() {
System.out.println("明星:歌唱~~~");
}
public void collectMoney() {
}
}
class Proxy implements Star {///代理类和被代理类实现同一套接口,帮被代理类去做事情,最后再加上被代理类的/独有的事情
private Star real;
public Proxy(Star real) {关键
this.real = real;
}
public void confer() {
System.out.println("经纪人面谈");
}
public void signContract() {
System.out.println("经纪人签合同");
}
public void bookTicket() {
System.out.println("经纪人订票");
}
public void sing() {
real.sing();
}
public void collectMoney() {
System.out.println("经纪人收钱");
}
}
public class Test5 {
public static void main(String[] args) {
Man man = new Man();
man.help();
}
}
interface Filial {// 孝顺的
default void help() {
System.out.println("老妈,我来救你了");
}
}
interface Spoony {// 痴情的
default void help() {
System.out.println("媳妇,别怕,我来了");
}
}
class Man implements Filial, Spoony {
@Override
public void help() {
System.out.println("我该怎么办呢?");
Filial.super.help();
Spoony.super.help();
}
}
这个创建内部类的对象时,一定要先创建外部类的对象,这样才能继续创建内部类的对象
package com.atguigu.java1;
class Father {
static {
System.out.println("11111111111");
}
{
System.out.println("22222222222");
}
public Father() {
System.out.println("33333333333");
}
}
public class Son extends Father {
static {
System.out.println("44444444444");
}
{
System.out.println("55555555555");
}
public Son() {
System.out.println("66666666666");
}
public static void main(String[] args) { // 由父及子 静态先行
System.out.println("77777777777");
System.out.println("************************");
new Son();
System.out.println("************************");
new Son();
System.out.println("************************");
new Father();
}
// 11111111111 //加载类信息的时候执行静态代码块
// 44444444444
// 77777777777
// ************************
// 22222222222
// 33333333333
// 55555555555
// 66666666666
// ************************
// 22222222222
// 33333333333
// 55555555555
// 66666666666
// ************************
// 22222222222
// 33333333333
}
public class Test1 {
public static void main(String[] args) {
A spring = A.SPRING;
System.out.println(spring.getDesc());
A winter = A.WINTER;
System.out.println(winter.getDesc());
}
}
/*
自定义枚举类
*/
class A{
private String name;
private String desc;
private A(String name, String desc) {
this.name = name;
this.desc = desc;
}
//这里SPRING直接属于A类,直接获取对象
//单例模式饿汉式中也属于A类,但是权限是私有的,只能调用公开的方法获取对象
public static final A SPRING = new A("春天","春暖花开");
public static final A WINTER = new A("冬天","寒冷");
public String getName() {
return name;
}
public String getDesc() {
return desc;
}
}
public class Test2 {
public static void main(String[] args) {
//1.Enum类name方法
Season spring = Season.SPRING;
System.out.println(spring.name());//SPRING
//2.Enum类中ordinal方法,看所属的常量排在第几位
System.out.println(spring.ordinal());//0
//3.Enum中values静态方法,得到所有的枚举对象的值
//4.Enum中toString方法已经重写
Season[] seasons = Season.values();
for(Season season : seasons){
System.out.println(season);//SPRING WINTER
}
//5.Enum类的静态方法valueOf方法,内部为变量名
Season spring1 = Season.valueOf("SPRING");
System.out.println(spring1);//SPRING
//比较枚举常量,比较的是编号
System.out.println(spring1.compareTo(spring));//0
}
}
enum Season{
SPRING("春天","春暖花开"),WINTER("冬天","寒冷");
private String name;
private String desc;
Season(String name, String desc) {
this.name = name;
this.desc = desc;
}
}
运行时异常,编译期没有错误,异常只有在在运行阶段才体现出体现出来
编译时异常,必须处理,否则程序通不过编译阶段,更谈不上运行
目的
捕获异常的相关信息⭐️
不捕获异常时的情况⭐️
public class MyExpTest {
public void regist(int num) throws MyException {
if (num < 0)
throw new MyException("人数为负值,不合理", 3);
else
System.out.println("登记人数" + num);
}
public void manager() {
try {
regist(100);
} catch (MyException e) {
System.out.print("登记失败,出错种类" + e.getId());
}
System.out.print("本次登记操作结束");
}
public static void main(String args[]) {
MyExpTest t = new MyExpTest();
t.manager();
}
}
class MyException extends Exception {
static final long serialVersionUID = 13465653435L;//重要
private int idnumber;
public MyException(String message, int id) {
super(message);//将异常信息传给父类,调用父类构造器
this.idnumber = id;
}
public int getId() {
return idnumber;
}
}
public class ReturnExceptionDemo {
static void methodA() {
try {
System.out.println("进入方法A");
throw new RuntimeException("制造异常");
}finally {
System.out.println("用A方法的finally");
}
}
static void methodB() {
try {
System.out.println("进入方法B");
return;//return之前也要调用finally方法,finally一定会执行
} finally {
System.out.println("调用B方法的finally");
}
}
public static void main(String[] args) {
try {
methodA();
} catch (Exception e) {
System.out.println(e.getMessage());
}
methodB();
}
// 进入方法A
// 用A方法的finally
// 制造异常
// 进入方法B
// 调用B方法的finally
}
public class Test1 {
public static void main(String[] args) {
Integer i1 = new Integer(127);
Integer i2 = new Integer(127);
System.out.println(i1 == i2);//false
System.out.println(i1.equals(i2));//true 比较的是内容
System.out.println("-----------");
Integer i3 = new Integer(128);
Integer i4 = new Integer(128);
System.out.println(i3 == i4);//false
System.out.println(i3.equals(i4));//true
System.out.println("-----------");
Integer i5 = 128;
Integer i6 = 128;
System.out.println(i5 == i6);//false
System.out.println(i5.equals(i6));//true
System.out.println("-----------");
Integer i7 = 127;
Integer i8 = 127;
System.out.println(i7 == i8);//true
System.out.println(i7.equals(i8));//true
// 由于我们要经常使用Integer类,所以他会提前为int型创建-128~127一共256个对象,
// 如果在自动装箱的时候给局部变量的int型值是在上面的范围之中,
// 就会直接将之前创建好的对象的地址值赋给等号左边的局部变量
//new 对象的时候不存在这一说法
// 在第一条中提到过,如果在自动装箱的时候给局部变量的int型值是在上面的范围之中,
// 就会直接将之前创建好的对象的地址值赋给等号左边的局部变量,
// 但是上述代码中在自动装箱时的int型值不在上述范围内,所以会重新new对象,既然会new,那么就不再指向同一个对象了,
// 所以System.out.println(i5 == i6);执行结果为false;
}
}
char[] a = {'a','b','c','d'};
String s = new String(a,0,2);//传入的必须是一个char型数组,不能直接传字符串
System.out.println(s);//ab
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qmK8T8Zx-1681915855129)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059947.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YbB9XVZO-1681915855130)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059949.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bg2lj1RA-1681915855130)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059950.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6w5K8qXA-1681915855131)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059952.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bqQ2KvLV-1681915855132)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059953.png)]
public class Test2 {
String str = new String("good");
char[] ch = { 't', 'e', 's', 't' };
public void change(String str, char ch[]) {
str = "test ok";
ch[0] = 'b';//传引用数值类型
}
public static void main(String[] args) {
Test2 ex = new Test2();
ex.change(ex.str, ex.ch);
System.out.print(ex.str + " and ");//good and best//分清楚局部变量和全局变量
System.out.println(ex.ch);
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EaAv8Ktl-1681915855133)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059956.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fuircoto-1681915855133)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059957.png)]
public class MethodTest {
@Test
public void test1(){
//char charAt()
String a = "abcd";
System.out.println(a.charAt(0));//a
//isEmpty();
System.out.println(a.isEmpty());//false
//String toUpperCase();
String a1 = a.toUpperCase(Locale.ROOT);
System.out.println(a1);//ABCD
//String trim()
String a2 = " abcd ";
String trim = a2.trim();
System.out.println(trim);//abcd
//boolean equalsIgnoreCase()
System.out.println(a1.equalsIgnoreCase(trim));//true
//String concat;
String a3 = a2.concat(trim);
System.out.println(a3);// abcd abcd
//compareTo
String in1 = "456";
String in2 = "356";
System.out.println(in1.compareTo(in2));//1表示,大于,4字符的字符值大于3
//String subString():返回子串
String substring = in1.substring(1);
System.out.println(substring);//56
String substring1 = in1.substring(1, 2);
System.out.println(substring1);//5
}
@Test
public void test2(){
//boolean endsWith()
String s1 = "我爱你中国爱你";
boolean is = s1.endsWith("中国");
System.out.println(is);//true
//boolean startsWith()
System.out.println(s1.startsWith("你", 2));//true
System.out.println(s1.startsWith("你", 1));//false
System.out.println("-----------------------");
//boolean contains()
System.out.println(s1.contains("中国"));//true
System.out.println("-----------------------");
//int indexOf():索引
int ind1 = s1.indexOf("爱你");
System.out.println(ind1);//1
int ind2 = s1.indexOf("爱你", 2);
System.out.println(ind2);//5
int end1 = s1.lastIndexOf("爱你");
System.out.println(end1);//5
int end2 = s1.lastIndexOf("爱你",4);
System.out.println(end2);//1
}
@Test
public void test3(){
//String replace()
String s1 = "哈哈哈哈哈哈哈哈你太可爱啦";
String s2 = s1.replace('哈', '呜');
System.out.println(s2);//呜呜呜呜呜呜呜呜你太可爱啦
String s3 = s1.replace("你太可爱", "你太漂亮");
System.out.println(s3);//哈哈哈哈哈哈哈哈你太漂亮啦
}
@Test
public void test4() throws UnsupportedEncodingException {
String str = "中";
System.out.println(str.getBytes("ISO8859-1").length);// -128~127 //1
System.out.println(str.getBytes("GBK").length);//2
System.out.println(str.getBytes("UTF-8").length);//3
System.out.println(new String(str.getBytes("ISO8859-1"),//乱码
"ISO8859-1"));// 乱码,表示不了中文
System.out.println(new String(str.getBytes("GBK"), "GBK"));//中
System.out.println(new String(str.getBytes("UTF-8"), "UTF-8"));//中,编码和解码结合在一块
// new String(str.getBytes("UTF-8"),"UTF-8");
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GwhHtxWp-1681915855135)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059961.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-F6vXIxr1-1681915855136)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059962.png)]
//对字符串中的字符进行排序
//将字符串变为数组,然后调用Arrays.sort()进行排序
String a = "654897894545613";
char[] chars = a.toCharArray();
Arrays.sort(chars);
System.out.println(chars);//134445556678899
a = new String(chars);
System.out.println(a);//134445556678899
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yGZgHNsQ-1681915855137)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059964.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mwjfMD9p-1681915855138)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059966.png)]
@Test
public void test1(){
StringBuffer buffer = new StringBuffer("abc");
//append();增
buffer.append("123");//可用buffer类接收
System.out.println(buffer);//abc123
//delete();删
buffer.delete(3,6);//[3,6)
System.out.println(buffer);
//replace();替换
buffer.replace(0,3,"def");
System.out.println(buffer);//def
//insert();插入
buffer.insert(3,"abc");
System.out.println(buffer);//defabc
//reverse();翻转
buffer.reverse();
System.out.println(buffer);//cbafed
}
@Test
public void test2(){
StringBuffer buffer = new StringBuffer("abc");
//indexOf()
int index = buffer.indexOf("bc");
System.out.println(index);//1
//subString():返回的是String类型的数据
String substring = buffer.substring(1, 3);
System.out.println(substring);//bc
//charAt()
//setCharAt()
buffer.setCharAt(1,'a');
System.out.println(buffer);//aac
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wPb48TVy-1681915855139)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059969.png)]
public class Test2 {
public static void main(String[] args) {
//初始设置
long startTime = 0L;
long endTime = 0L;
String text = "";
StringBuffer buffer = new StringBuffer("");
StringBuilder builder = new StringBuilder("");
//开始对比
startTime = System.currentTimeMillis();
for (int i = 0; i < 200000; i++) {
buffer.append(String.valueOf(i));
}
endTime = System.currentTimeMillis();
System.out.println("StringBuffer的执行时间:" + (endTime - startTime));
startTime = System.currentTimeMillis();
for (int i = 0; i < 200000; i++) {
builder.append(String.valueOf(i));
}
endTime = System.currentTimeMillis();
System.out.println("StringBuilder的执行时间:" + (endTime - startTime));
startTime = System.currentTimeMillis();
for (int i = 0; i < 200000; i++) {
text = text + i;//每次都是创建一个对象
}
endTime = System.currentTimeMillis();
System.out.println("String的执行时间:" + (endTime - startTime));
}
}
StringBuffer的执行时间:6
StringBuilder的执行时间:0
String的执行时间:3817
public class Test3 {
public static void main(String[] args) {
String str = null;
StringBuffer sb = new StringBuffer();
sb.append(str);
System.out.println(str);//null
System.out.println(sb.length());//4
System.out.println(sb);//null
StringBuffer sb1 = new StringBuffer(str);
System.out.println(sb1);//报错
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CExwjgG6-1681915855140)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059971.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aIerx1av-1681915855142)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059975.png)]
Date date = new Date();
System.out.println(date);//Mon Dec 26 19:33:24 CST 2022
System.out.println(System.currentTimeMillis());//1672054404487
System.out.println(date.getTime());//1672054404467
Date date1 = new Date(date.getTime());
System.out.println(date1.getTime());//1672054404467
System.out.println(date1.toString());//Mon Dec 26 19:33:24 CST 2022
public class Format {
public static void main(String[] args) {
Date date = new Date(); // 产生一个Date实例
// 产生一个formater格式化的实例
SimpleDateFormat formater = new SimpleDateFormat();
System.out.println(formater.format(date));// 打印输出默认的格式2022/12/26 下午7:41
SimpleDateFormat formater2 = new SimpleDateFormat("YYYY:MM:dd:HH:mm:ss");
System.out.println(formater2.format(date));//2022:12:26:19:41:05放入Date类型后,解析成想要输出的格式
try {
// 实例化一个指定的格式对象
Date date2 = formater2.parse("2022:12:26:10:50:20");
// 将指定的日期解析后格式化按指定的格式输出
System.out.println(date2.toString());//Sun Dec 26 10:50:20 CST 2021
} catch (ParseException e) {
e.printStackTrace();
}
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-29PpIics-1681915855144)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059978.png)]
public class CalendarTest {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
// 从一个 Calendar 对象中获取 Date 对象
Date date = calendar.getTime();
// 使用给定的 Date 设置此 Calendar 的时间
date = new Date(234234235235L);
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_MONTH, 8);
System.out.println("当前时间日设置为8后,时间是:" + calendar.getTime());//当前时间日设置为8后,时间是:Wed Jun 08 09:03:55 CST 1977
calendar.add(Calendar.HOUR, 2);
System.out.println("当前时间加2小时后,时间是:" + calendar.getTime());//当前时间加2小时后,时间是:Wed Jun 08 11:03:55 CST 1977
calendar.add(Calendar.MONTH, -2);
System.out.println("当前日期减2个月后,时间是:" + calendar.getTime());//当前日期减2个月后,时间是:Fri Apr 08 11:03:55 CST 1977
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lpCtQuGm-1681915855146)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059981.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lg7PYm5S-1681915855146)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059982.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-k7iGi0ch-1681915855147)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059984.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Bgf4WMup-1681915855149)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059987.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-L30igIsv-1681915855150)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059990.png)]
public class Goods implements Comparable{
private String name;
private double price;
public Goods() {
}
public Goods(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Goods{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
@Override
public int compareTo(Object o) {
if(o instanceof Goods){
Goods other = (Goods) o;
if(this.price > other.price){
return 1;
}else if(this.price < other.price){
return -1;
}
return 0;
}
throw new RuntimeException("输入类型不匹配");
}
}
public class ComparableTest {
public static void main(String[] args) {
Goods[] all = new Goods[4];
all[0] = new Goods("《红楼梦》", 100);
all[1] = new Goods("《西游记》", 80);
all[2] = new Goods("《三国演义》", 140);
all[3] = new Goods("《水浒传》", 120);
Arrays.sort(all);
System.out.println(Arrays.toString(all));//[Goods{name='《西游记》', price=80.0}, Goods{name='《红楼梦》', price=100.0},
// Goods{name='《水浒传》', price=120.0}, Goods{name='《三国演义》', price=140.0}]
}
}
public class ComparatorTest {
public static void main(String[] args) {
Goods[] all = new Goods[4];
all[0] = new Goods("War and Peace", 100);
all[1] = new Goods("Childhood", 80);
all[2] = new Goods("Scarlet and Black", 140);
all[3] = new Goods("Notre Dame de Paris", 120);
Arrays.sort(all, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
Goods g1 = (Goods) o1;
Goods g2 = (Goods) o2;
//按名字来排序
return g1.getName().compareTo(g2.getName());
}
});
System.out.println(Arrays.toString(all));
}
}
public class Test {
public static void main(String[] args) {
String javaVersion = System.getProperty("java.version");
System.out.println("java的version:" + javaVersion);
String javaHome = System.getProperty("java.home");
System.out.println("java的home:" + javaHome);
String osName = System.getProperty("os.name");
System.out.println("os的name:" + osName);
String osVersion = System.getProperty("os.version");
System.out.println("os的version:" + osVersion);
String userName = System.getProperty("user.name");
System.out.println("user的name:" + userName);
String userHome = System.getProperty("user.home");
System.out.println("user的home:" + userHome);
String userDir = System.getProperty("user.dir");
System.out.println("user的dir:" + userDir);
// java的version:11.0.16
// java的home:D:\Environment\Java\jdk11
// os的name:Windows 10
// os的version:10.0
// user的name:666
// user的home:C:\Users\666
// user的dir:D:\desktop\666\study\Java\javaseReverse
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FyjL8HJw-1681915855154)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059998.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EAwOu195-1681915855155)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059999.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cVVgShPf-1681915855155)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059000.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ggqd8lwE-1681915855156)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059001.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3K7M2Yxc-1681915855156)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059002.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IISRF7RR-1681915855157)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059003.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Pkprnucg-1681915855157)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059004.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-os2jPi13-1681915855158)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059006.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fcBwydMo-1681915855159)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059008.png)]
public class Test1 {
public static void main(String[] args) {
Collection coll = new ArrayList();
coll.add("AA");
coll.add("BB");
coll.add(123);
coll.add(new Date());
System.out.println(coll.size());//4
Collection coll1 = new ArrayList();
coll1.add(456);
coll1.add("CC");
coll.addAll(coll1);
System.out.println(coll.size());//6
System.out.println(coll);//[AA, BB, 123, Tue Dec 27 20:52:51 CST 2022, 456, CC]
coll.clear();
System.out.println(coll.isEmpty());//true
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UNYBUbMS-1681915855161)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059013.png)]
//移除字符串中的2元素
public class Test1 {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
arrayList.add(new String(String.valueOf(i)));
}
Iterator<String> iterator = arrayList.iterator();
while(iterator.hasNext()){
if(iterator.next().equals("2")){
iterator.remove();
}
}
for(String s : arrayList){
System.out.print(s + " ");//0 1 3 4
}
}
}
public class MethodTest {
@Test
public void test1() {
Collection coll = new ArrayList();
coll.add(123);
coll.add(456);
coll.add(new String("Tom"));
coll.add(false);
coll.add(new Person("Jerry", 20));
boolean contains = coll.contains(123);
System.out.println(contains);//true
System.out.println(coll.contains(new String("Tom")));//true
System.out.println(coll.contains(new Person("Jerry", 20)));//false
//contains内部还是比较equals方法,String重写了equals方法,所以比较的是内容,而Person比较的是地址
Collection coll1 = Arrays.asList(123, 456);
System.out.println(coll.containsAll(coll1));//true
}
@Test
public void test2() {
Collection coll = new ArrayList();
coll.add(123);
coll.add(456);
coll.add(new Person("Jerry", 20));
coll.add(new String("Tom"));
coll.add(false);
System.out.println(coll);//[123, 456, day05.Colltection.Person@3891771e, Tom, false]
coll.remove(new Person("Jerry", 20));
Collection coll1 = Arrays.asList(123, 456);
coll.removeAll(coll1);
//remove移除元素判断的还是底层的equals方法
System.out.println(coll);//[day05.Colltection.Person@3891771e, Tom, false]
}
@Test
public void test3() {
Collection coll = new ArrayList();
coll.add(123);
coll.add(456);
coll.add(new Person("Jerry", 20));
coll.add(new String("Tom"));
coll.add(false);
Collection coll1 = new ArrayList();
coll1.add(123);
coll1.add(456);
coll1.add(new Person("Jerry", 20));
coll1.add(new String("Tom"));
coll1.add(false);
//coll.equals方法经过重写,还是调用每一个对象的equals方法比较
System.out.println(coll.equals(coll1));//false
}
@Test
public void test4() {
Collection coll = new ArrayList();
coll.add(123);
coll.add(456);
coll.add(new Person("Jerry", 20));
coll.add(new String("Tom"));
coll.add(false);
System.out.println(coll.hashCode());
Object[] arr = coll.toArray();
for(int i = 0; i < arr.length; ++i) {
System.out.println(arr[i]);
}
List<String> list = Arrays.asList("AA", "BB", "CC");
System.out.println(list);
Iterator var4 = list.iterator();
while(var4.hasNext()) {
String l = (String)var4.next();
System.out.println(l);
}
List arr1 = Arrays.asList(new int[]{123, 456});
System.out.println(arr1.size());//1,就一个数组元素
System.out.println(arr1);
List arr2 = Arrays.asList(123, 456);
//接收参数是一个可变形参数组
//return new ArrayList<>(a);两个元素
System.out.println(arr2.size());//2
}
}
class Person{
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person() {
}
}
@Test
public void test2() {
Collection coll = new ArrayList();
coll.add(123);
coll.add(456);
coll.add(new Person("Jerry", 20));
coll.add(new String("Tom"));
coll.add(false);
//这里会出错,因为每次调用iterator都会生成一个新的迭代器,所以会无限循环
while(coll.iterator().hasNext()) {
System.out.println(coll.iterator().next());
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-y2Uv9sJX-1681915855161)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059014.png)]
增:add(Object obj)
删:remove(int index) / remove(Object obj)
改:set(int index, Object ele)
查:get(int index)
插:add(int index, Object ele)
长度:size()
遍历:① Iterator迭代器方式
② 增强for循环
③ 普通的循环
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rFEa1LOC-1681915855163)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059017.png)]
public class Test {
@org.junit.Test
public void test3() {
ArrayList list = new ArrayList();
list.add(123);
list.add(456);
list.add("AA");
Iterator iterator = list.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
// 123
// 456
// AA
System.out.println("**************");
Iterator var3 = list.iterator();
while(var3.hasNext()) {
Object obj = var3.next();
System.out.println(obj);
}
// 123
// 456
// AA
System.out.println("**************");
for(int i = 0; i < list.size(); ++i) {
System.out.println(list.get(i));
}
}
@org.junit.Test
public void test2() {
ArrayList list = new ArrayList();
list.add(123);
list.add(456);
list.add("AA");
list.add(new Person("Tom", 12));
list.add(456);
int index = list.indexOf(456);
System.out.println(index);//1
System.out.println(list.lastIndexOf(456));//4
Object obj = list.remove(0);
System.out.println(obj);//123
System.out.println(list);//[456, AA, day05.ListTest.Person@3891771e, 456]
list.set(1, "CC");
System.out.println(list);//[456, CC, day05.ListTest.Person@3891771e, 456]
List subList = list.subList(2, 4);
System.out.println(subList);//[day05.ListTest.Person@3891771e, 456]
}
@org.junit.Test
public void test1() {
ArrayList list = new ArrayList();
list.add(123);
list.add(456);
list.add("AA");
list.add(new Person("Tom", 12));
list.add(456);
//可重复
System.out.println(list);//[123, 456, AA, day05.ListTest.Person@3891771e, 456]
//添加到1处,"BB"
list.add(1, "BB");
System.out.println(list);//[123, BB, 456, AA, day05.ListTest.Person@3891771e, 456]
List list1 = Arrays.asList(1, 2, 3);
list.addAll(list1);
System.out.println(list.size());//9
System.out.println(list);//[123, BB, 456, AA, day05.ListTest.Person@3891771e, 456, 1, 2, 3]
System.out.println(list.get(0));//123
}
}
class Person{
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person() {
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hpy8mDJf-1681915855163)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059018.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Hj34hIMp-1681915855164)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059020.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4QsGetJw-1681915855165)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059021.jpg)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3EmaX4qN-1681915855165)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059022.jpg)]
public class ArrayListTest {
public static void testListRemove() {
List list = new ArrayList();
list.add(1);
list.add(2);
list.add(3);
updateList(list);
System.out.println(list);//[1, 2]
}
private static void updateList(List list) {
list.remove(2);
}
public static void main(String[] args) {
testListRemove();
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-a9VrMTLD-1681915855166)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059023.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VE0sLaYK-1681915855167)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059024.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-O4yNnaz9-1681915855168)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059025.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AkDJefuN-1681915855168)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059026.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-O8dEPDq6-1681915855169)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059027.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9YthTbqq-1681915855170)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059028.png)]
无序性:不等于随机性。存储的数据在底层数组中并非照数组索引的顺序添加,而是根据数据的哈希值决定的。
不可重复性:保证添加的元素照equals()判断时,不能返回true.即:相同的元素只能添加一个。
所以要添加自定义的对象时,一定要重写hashcode()和equals()方法,添加自定义对象时先判断hashcode如果不一样,那么不判断equals()方法,认为不一样。这样可以提高判断效率。因此要重写hashcode和equals方法
可以理解为hashcode是第一关,第一关通过第二关equals方法再通过,就完全相同。
Object中的hashcode()方法没有属性依据随机随机算得一个数,所以调用的话hashcode值不会一样
总之一定要保证相等的对象有相同的hashcode
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tuW3U3bj-1681915855171)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059029.png)]
2.元素添加过程:(以HashSet为例)
散列函数计算还尽可能保证能均匀存储元素
3.底层结构:散列数组 + 链表
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hLHF1Snw-1681915855172)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059030.png)]
4.Set接口中的方法都是Colltecion中的方法,没有修改的方法
5.因为Set接口的值不可重复,Map接口中key不可重复,所以都有Tree结构进行排序
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rse5OJis-1681915855172)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059031.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hqCOBtiG-1681915855173)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059032.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Pa8hPcDX-1681915855174)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059033.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MTMAkMS3-1681915855175)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059034.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9pWpV2z8-1681915855176)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059035.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5dTCP5n9-1681915855177)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059036.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6O0lYPS5-1681915855177)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059037.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Vj3IEACY-1681915855178)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059038.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gZ18XjZ0-1681915855179)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059041.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TvCMAYXu-1681915855180)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059043.png)]
1.一般使用HashMap,HashMap的线程不安全性,可由Collections工具类来解决
2.TreeMap排序的时候,考虑key的自然排序和定制排序
3.底层结构⭐️ 数组 + 链表 + 存储元素(entry或node)
4.内部类只能对外部类范围内有效,只能使用外部类中的成员,与别的成员无联系,所以声明为内部类
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qJpWds6w-1681915855182)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059046.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ykbPaSLC-1681915855184)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059049.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hcVGZDQu-1681915855184)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059050.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-btnAMYSA-1681915855185)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059051.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-iLpvR8Or-1681915855188)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059055.png)]
以上为jdk7
总结:常用方法:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JTdEIx8t-1681915855191)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059061.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2LBwXnyF-1681915855193)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059064.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YXHyyuTB-1681915855193)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059065.png)]
/*
添加、删除、修改操作:
Object put(Object key,Object value):将指定key-value添加到(或修改)当前map对象中
void putAll(Map m):将m中的所有key-value对存放到当前map中
Object remove(Object key):移除指定key的key-value对,并返回value
void clear():清空当前map中的所有数据
*/
@Test
public void test3(){
Map map = new HashMap();
//添加
map.put("AA",123);
map.put(45,123);
map.put("BB",56);
//修改
///
map.put("AA",87);//重复添加相同的key,会修改value
System.out.println(map);//{AA=87, BB=56, 45=123}
Map map1 = new HashMap();
map1.put("CC",123);
map1.put("DD",123);
map.putAll(map1);
System.out.println(map);
//remove(Object key)
Object value = map.remove("CC");
System.out.println(value);//123,返回要移除的键值对的value
System.out.println(map);//{AA=87, BB=56, DD=123, 45=123}
//clear()
map.clear();//与map = null操作不同
System.out.println(map.size());//0,map还在,只是将里面存的数据清除
System.out.println(map);//{}
}
/*
元素查询的操作:
Object get(Object key):获取指定key对应的value
boolean containsKey(Object key):是否包含指定的key
boolean containsValue(Object value):是否包含指定的value
int size():返回map中key-value对的个数
boolean isEmpty():判断当前map是否为空
boolean equals(Object obj):判断当前map和参数对象obj是否相等
*/
@Test
public void test4(){
Map map = new HashMap();
map.put("AA",123);
map.put(45,123);
map.put("BB",56);
// Object get(Object key)
System.out.println(map.get(45));//123
//containsKey(Object key)
boolean isExist = map.containsKey("BB");
System.out.println(isExist);
isExist = map.containsValue(123);
System.out.println(isExist);
map.clear();
System.out.println(map.isEmpty());//true
}
@Test
public void test5(){
Map map = new HashMap();
map.put("AA",123);
map.put(45,1234);
map.put("BB",56);
//遍历所有的key集:keySet()
Set set = map.keySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
//AA BB 45
System.out.println();
//遍历所有的value集:values()
Collection values = map.values();
for(Object obj : values){
System.out.println(obj);
}
System.out.println();
//遍历所有的key-value
//方式一:entrySet()
Set entrySet = map.entrySet();
Iterator iterator1 = entrySet.iterator();
while (iterator1.hasNext()){
Object obj = iterator1.next();
//entrySet集合中的元素都是entry
Map.Entry entry = (Map.Entry) obj;
System.out.println(entry.getKey() + "---->" + entry.getValue());
}
System.out.println();
//方式二:
Set keySet = map.keySet();
Iterator iterator2 = keySet.iterator();
while(iterator2.hasNext()){
Object key = iterator2.next();
Object value = map.get(key);
System.out.println(key + "=====" + value);
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-DuL6pOvM-1681915855194)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059066.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JKvKR9Dt-1681915855194)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059067.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NcBf4LfM-1681915855195)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059068.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zOcz0Jn5-1681915855196)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059069.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Xjn9vzpR-1681915855196)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059070.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0aQsB3VM-1681915855197)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059071.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wTqPFgNW-1681915855197)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059072.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NseCTWNS-1681915855198)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059073.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WStRcZDl-1681915855198)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059074.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-71sftptU-1681915855199)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059075.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vDgdd0pq-1681915855199)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059076.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ImUYHQLZ-1681915855200)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059077.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TbplKZ4R-1681915855200)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059078.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VaAwkfRz-1681915855200)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059079.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MKa1CcIw-1681915855200)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059080.png)]
public class User implements Comparable{
private String name;
private int age;
public User() {
}
public User(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 "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
System.out.println("User equals()....");
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
if (age != user.age) return false;
return name != null ? name.equals(user.name) : user.name == null;
}
@Override
public int hashCode() { //return name.hashCode() + age;
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
return result;
}
//按照姓名从大到小排列,年龄从小到大排列
@Override
public int compareTo(Object o) {
if(o instanceof User){
User user = (User)o;
// return -this.name.compareTo(user.name);
int compare = -this.name.compareTo(user.name);
if(compare != 0){
return compare;
}else{
return Integer.compare(this.age,user.age);
}
}else{
throw new RuntimeException("输入的类型不匹配");
}
}
}
//向TreeMap中添加key-value,要求key必须是由同一个类创建的对象
//因为要按照key进行排序:自然排序 、定制排序
//自然排序
@Test
public void test1(){
TreeMap map = new TreeMap();
User u1 = new User("Tom",23);
User u2 = new User("Jerry",32);
User u3 = new User("Jack",20);
User u4 = new User("Rose",18);
map.put(u1,98);
map.put(u2,89);
map.put(u3,76);
map.put(u4,100);
Set entrySet = map.entrySet();
Iterator iterator1 = entrySet.iterator();
while (iterator1.hasNext()){
Object obj = iterator1.next();
Map.Entry entry = (Map.Entry) obj;
System.out.println(entry.getKey() + "---->" + entry.getValue());
}
// User{name='Tom', age=23}---->98
// User{name='Rose', age=18}---->100
// User{name='Jerry', age=32}---->89
// User{name='Jack', age=20}---->76
}
//定制排序
@Test
public void test2(){
TreeMap map = new TreeMap(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if(o1 instanceof User && o2 instanceof User){
User u1 = (User)o1;
User u2 = (User)o2;
return Integer.compare(u1.getAge(),u2.getAge());
}
throw new RuntimeException("输入的类型不匹配!");
}
});
User u1 = new User("Tom",23);
User u2 = new User("Jerry",32);
User u3 = new User("Jack",20);
User u4 = new User("Rose",18);
map.put(u1,98);
map.put(u2,89);
map.put(u3,76);
map.put(u4,100);
Set entrySet = map.entrySet();
Iterator iterator1 = entrySet.iterator();
while (iterator1.hasNext()){
Object obj = iterator1.next();
Map.Entry entry = (Map.Entry) obj;
System.out.println(entry.getKey() + "---->" + entry.getValue());
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8E8qBcQC-1681915855201)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059081.png)]
public class Properties {
//Properties:常用来处理配置文件。key和value都是String类型
public static void main(String[] args) {
FileInputStream fis = null;
try {
java.util.Properties pros = new java.util.Properties();
fis = new FileInputStream("jdbc.properties");
pros.load(fis);//加载流对应的文件
String name = pros.getProperty("name");
String password = pros.getProperty("password");
System.out.println("name = " + name + ", password = " + password);
//name = Tom宋红康, password = abc123
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
操作Collection和Map的工具类
排序方法都是针对List接口的 Arrays工具类针对数组排序
size()方法表示存了几个元素
将集合转变为同步的方法synchronizedList()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JlDcWplJ-1681915855202)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059082.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rsLQrNfC-1681915855202)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059083.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LviVSNTz-1681915855203)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059084.png)]
/*
reverse(List):反转 List 中元素的顺序
shuffle(List):对 List 集合元素进行随机排序
sort(List):根据元素的自然顺序对指定 List 集合元素按升序排序
sort(List,Comparator):根据指定的 Comparator 产生的顺序对 List 集合元素进行排序
swap(List,int, int):将指定 list 集合中的 i 处元素和 j 处元素进行交换
Object max(Collection):根据元素的自然顺序,返回给定集合中的最大元素
Object max(Collection,Comparator):根据 Comparator 指定的顺序,返回给定集合中的最大元素
Object min(Collection)
Object min(Collection,Comparator)
int frequency(Collection,Object):返回指定集合中指定元素的出现次数
void copy(List dest,List src):将src中的内容复制到dest中
boolean replaceAll(List list,Object oldVal,Object newVal):使用新值替换 List 对象的所有旧值
*/
@Test
public void test2(){
List list = new ArrayList();
list.add(123);
list.add(43);
list.add(765);
list.add(-97);
list.add(0);
//报异常:IndexOutOfBoundsException("Source does not fit in dest")
// List dest = new ArrayList();//这里如果指定长度,那么指定的是底层数组造了几个,而不是实际存的元素
// Collections.copy(dest,list);
//正确的:
List dest = Arrays.asList(new Object[list.size()]);
System.out.println(dest.size());//list.size(); //5
Collections.copy(dest,list);
System.out.println(dest);//[123, 43, 765, -97, 0]
/*
Collections 类中提供了多个 synchronizedXxx() 方法,
该方法可使将指定集合包装成线程同步的集合,从而可以解决
多线程并发访问集合时的线程安全问题
*/
//返回的list1即为线程安全的List
List list1 = Collections.synchronizedList(list);
}
@Test
public void test1(){
List list = new ArrayList();
list.add(123);
list.add(43);
list.add(765);
list.add(765);
list.add(765);
list.add(-97);
list.add(0);
System.out.println(list);//[123, 43, 765, 765, 765, -97, 0]
// Collections.reverse(list);
// Collections.shuffle(list);
// Collections.sort(list);
// Collections.swap(list,1,2);
int frequency = Collections.frequency(list, 123);
System.out.println(list);//[123, 43, 765, 765, 765, -97, 0]
System.out.println(frequency);//1
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-X7JR8lK8-1681915855203)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059086.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rxcxJqFq-1681915855205)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059089.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2PdWwTBu-1681915855206)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059092.png)]
ArrayList<Integer> list = new ArrayList<>();//类型推断
list.add(78);
list.add(88);
list.add(77);
list.add(66);
//遍历方式一:
//for(Integer i : list){
//不需要强转
//System.out.println(i);
//}
//遍历方式二:
Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("Tom1",34);
map.put("Tom2",44);
map.put("Tom3",33);
map.put("Tom4",32);
//添加失败
//map.put(33, "Tom");
Set<Entry<String,Integer>> entrySet = map.entrySet();
Iterator<Entry<String,Integer>> iterator = entrySet.iterator();
while(iterator.hasNext()){
Entry<String,Integer> entry = iterator.next();
System.out.println(entry.getKey() + "--->" + entry.getValue());
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0ok8zBIC-1681915855206)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059093.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HUqOUDTr-1681915855208)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059096.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pUkUKceW-1681915855208)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059097.png)]
class 类名称 <泛型标识:可以随便写任意标识号,标识指定的泛型的类型>{
private 泛型标识 /*(成员变量类型)*/ var;
.....
}
}
//此处T可以随便写为任意标识,常见的如T、E、K、V等形式的参数常用于表示泛型
//在实例化泛型类时,必须指定T的具体类型,否则T为Object类型
public class Generic<T>{
//key这个成员变量的类型为T,T的类型由外部指定
private T key;
public Generic(T key) { //泛型构造方法形参key的类型也为T,T的类型由外部指定
this.key = key;
}
public T getKey(){ //泛型方法getKey的返回值类型为T,T的类型由外部指定
return key;
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gfWFlwib-1681915855210)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059100.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sAk6wlSj-1681915855210)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059101.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bBMBliBZ-1681915855211)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059102.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-l2WgOY0W-1681915855211)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059103.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1GjUuKwO-1681915855212)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059104.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-E5MMNyRR-1681915855212)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059105.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zltiDc03-1681915855213)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059106.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lgEftlur-1681915855213)(https://weifengqin-image.oss-cn-nanjing.aliyuncs.com/img/202304180059107.png)]
/*
3.有限制条件的通配符的使用。
? extends A:
G extends A> 可以作为G和G的父类,其中B是A的子类
? super A:
G super A> 可以作为G和G的父类,其中B是A的父类
*/
@Test
public void test4(){
List<? extends Person> list1 = null;
List<? super Person> list2 = null;
List<Student> list3 = new ArrayList<Student>();
List<Person> list4 = new ArrayList<Person>();
List<Object> list5 = new ArrayList<Object>();
list1 = list3;
list1 = list4;
// list1 = list5;
// list2 = list3;
list2 = list4;
list2 = list5;
//读取数据:
list1 = list3;
Person p = list1.get(0);//可以用Person,Object,因为小于等于Person
//编译不通过
//Student s = list1.get(0);//因为不确定是不是Student/重要///
list2 = list4;
Object obj = list2.get(0);//这里只能是Object,因为大于等于Person,Object能确定
编译不通过
// Person obj = list2.get(0);
//写入数据:
//编译不通过
// list1.add(new Student());
//编译通过
list2.add(new Person());//这里就可以往小的写,因为最小是Person,你只要往里传Person子类就可以
list2.add(new Student());
}
图片转存中…(img-3iLUjsKg-1681915855214)]
[外链图片转存中…(img-W1ZQ5wOT-1681915855214)]
[外链图片转存中…(img-2Z4u4gBE-1681915855215)]
[外链图片转存中…(img-0xd0Fz00-1681915855216)]
[外链图片转存中…(img-0EnPPJqC-1681915855216)]
[外链图片转存中…(img-hhsRUXYs-1681915855216)]
[外链图片转存中…(img-MkcMESUz-1681915855217)]
[外链图片转存中…(img-mH32zGXw-1681915855217)]
[外链图片转存中…(img-nmBwaz0n-1681915855218)]
[外链图片转存中…(img-mRiEz0tI-1681915855218)]
[外链图片转存中…(img-0IoNK78Z-1681915855218)]
[外链图片转存中…(img-0zT9udOA-1681915855219)]
同一个类型不同泛型之间没关系,但是不同类型,同一种泛型之间有子父类关系
[外链图片转存中…(img-fP8fz3gU-1681915855220)]
[外链图片转存中…(img-E49HOR7b-1681915855220)]
[外链图片转存中…(img-b097q7su-1681915855221)]
[外链图片转存中…(img-ENU0qh1h-1681915855221)]
[外链图片转存中…(img-ZgCugI5A-1681915855222)]
通配符
通配符是泛型<>的通用父类
[外链图片转存中…(img-C4TDkXXp-1681915855222)]
[外链图片转存中…(img-Uzmz0AYz-1681915855223)]
[外链图片转存中…(img-S6oFZWYg-1681915855223)]
通配符:写入
[外链图片转存中…(img-30GNC9NC-1681915855224)]
通配符:读取
[外链图片转存中…(img-2qx26DO7-1681915855224)]
有限制条件的通配符
?(-…,+…) extends <= super >=
[外链图片转存中…(img-fROlq9MX-1681915855225)]
/*
3.有限制条件的通配符的使用。
? extends A:
G extends A> 可以作为G和G的父类,其中B是A的子类
? super A:
G super A> 可以作为G和G的父类,其中B是A的父类
*/
@Test
public void test4(){
List<? extends Person> list1 = null;
List<? super Person> list2 = null;
List<Student> list3 = new ArrayList<Student>();
List<Person> list4 = new ArrayList<Person>();
List<Object> list5 = new ArrayList<Object>();
list1 = list3;
list1 = list4;
// list1 = list5;
// list2 = list3;
list2 = list4;
list2 = list5;
//读取数据:
list1 = list3;
Person p = list1.get(0);//可以用Person,Object,因为小于等于Person
//编译不通过
//Student s = list1.get(0);//因为不确定是不是Student/重要///
list2 = list4;
Object obj = list2.get(0);//这里只能是Object,因为大于等于Person,Object能确定
编译不通过
// Person obj = list2.get(0);
//写入数据:
//编译不通过
// list1.add(new Student());
//编译通过
list2.add(new Person());//这里就可以往小的写,因为最小是Person,你只要往里传Person子类就可以
list2.add(new Student());
}
[外链图片转存中…(img-szU59kNK-1681915855225)]