day03 - Java集合和常用类

news2024/9/21 2:40:48

第一章 Collection集合

1. Collection概述

集合:java中提供的一种容器,可以用来存储多个数据
集合和数组既然都是容器,它们有啥区别呢?

  • 数组的长度是固定的。集合的长度是不固定的。集合可以随时增加元素,其大小也随之增加
  • 数组中存储的是同一类型的元素,可以存储基本数据类型值。集合存储的都是对象。而且对象的类型可以不一致。在开发中一般当对象多的时候,使用集合进行存储
  • 集合除了可以通过角标操作外,还具有其它操作元素的方式

2. 集合框架

集合按照其存储结构可以分为两大类,分别是单列集合java.util.Collection和双列集合java.util.Map
集合框架
简化图
集合框架简化图

  • Collection:单列集合类的根接口,用于存储一系列符合某种规则的元素,它有两个重要的子接口,分 别是java.util.List 和java.util.Set
  • List 的特点是元素有序、元素可重复。List 接口的主要实现类有java.util.ArrayListjava.util.LinkedList
  • Set 的特点是元素无序,而且不可重复。Set 接口的主要实现类有java.util.HashSetjava.util.TreeSet

3. 常用功能

Collection是所有单列集合的父接口,在Collection中定义的通用方法,可用于操作所有的单列集合

方法名说明
boolean add(E e)添加元素
boolean remove(Object o)从集合中移除指定的元素
void clear()清空集合中的元素
boolean contains(Object o)判断集合中是否存在指定的元素
boolean isEmpty()判断集合是否为空
int size()集合的长度,也就是集合中元素的个数
Object[] toArray()把集合中的元素,存储到数组中

例:

    public static void main(String[] args) {
        Collection<String> list = new ArrayList<String>();

        list.add("张三");
        list.add("王五");

        System.out.println("集合中是否包含小二:"+list.contains("小二"));

        Object[] str = list.toArray();
        for(Object o:str){
            System.out.println(o);
        }

        list.remove("张三");
        System.out.println("集合中元素个数:"+list.size());
        if(!list.isEmpty()){
            list.clear();
        }
        System.out.println("集合中元素个数:"+list.size());
    }

结果:

集合中是否包含小二:false
张三
王五
集合中元素个数:1
集合中元素个数:0

第二章 Iterator迭代器

1. Iterator接口

想要遍历Collection集合,那么就要获取该集合迭代器完成迭代操作,可以对集合中的元素进行删除操作

public Iterator iterator(): //获取集合对应的迭代器,用来遍历集合中的元素

Iterator接口的常用方法如下:

方法名说明
public E next()返回迭代的下一个元素。
public boolean hasNext()如果仍有元素可以迭代,则返回 true
void remove()删除迭代器对象当前指向的元素

如果集合中没有元素,还使用迭代器的next方法,将会发生java.util.NoSuchElement
Exception
没有集合元素的错误
例:

    public static void main(String[] args) {
        Collection<String> list = new ArrayList<String>();
        list.add("张三");
        list.add("王五");
        list.add("李四");
        list.add("老六");
         //迭代器就好比是一个指针,默认指向集合的0索引处
        Iterator<String> it = list.iterator();
        while(it.hasNext()){
            String str = it.next();//获取元素并移动指针
            if("老六".equals(str)){
                it.remove();//删除当前指向
            }
            System.out.println("元素:"+str);
        } //迭代器遍历完毕,指针不会复位,再次使用,就新建迭代器对象
        System.out.println("集合元素:"+list);
    }

结果:

元素:张三
元素:王五
元素:李四
元素:老六
集合元素:[张三, 王五, 李四]

2. 增强for

增强for循环(也称for each循环)是JDK1.5以后出来的一个高级for循环,专门用来遍历数组和集合的。它
的内部原理其实是个Iterator迭代器,所以在遍历的过程中,不能对集合中的元素进行增删操作。实现
Iterable接口的类才可以使用迭代器和增强for
格式:

 for(元素的数据类型  变量 : Collection集合or数组){ 
    //操作区
}

例:

public class CollectionTest {
    public static void main(String[] args) {
        Collection<String> list = new ArrayList<String>();
        list.add("张三");
        list.add("王五");
        list.add("李四");
        list.add("老六");
        for (String str:list) {
            System.out.println(str);
        }
    }
}

结果:

张三
王五
李四
老六

3. 注意事项

  • 报错NoSuchElementException (集合中没有元素,还使用迭代器的next方法)
  • 迭代器遍历完毕,指针不会复位
  • 循环中只能用一次next方法
  • 迭代器遍历时,不能用集合的方法进行增加或者删除
  • 增强for循环必须有被遍历的目标。目标只能是Collection或者是数组。增强for仅仅作为遍历操作出现

第三章 List集合

1. List集合特点

  1. 元素可重复(可用元素的equals方法,来比较是否为重复的元素)
  2. 元素有序,即元素的存入顺序和取出顺序一致
  3. 带有索引的集合,通过索引就可以精确的操作集合中的元素

2. 常用方法

方法名描述
void add(int index,E element)在此集合中的指定位置插入指定的元素
E remove(int index)删除指定索引处的元素,返回被删除的元素
E set(int index,E element)修改指定索引处的元素,返回被修改的元素
E get(int index)返回指定索引处的元素

例:

public class CollectionTest {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        list.add("张三");
        list.add("王五");
        list.add("李四");
        list.add(1,"老六");
        System.out.println(list.get(1));
        System.out.println(list.set(1,"老五"));
        list.remove(0);
        System.out.println(list.get(1));
        for (String str:list) {
            System.out.println(str);
        }
    }
}

结果;

老六
老六
王五
老五
王五
李四

3. List集合的五种遍历方式

  1. 迭代器
  2. 列表迭代器(在迭代器原有方法上,新增可以添加元素的方法)
  3. 增强for
  4. Lambda表达式
  5. 普通for循环
public class CollectionTest {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        list.add("张三");
        list.add("王五");
        list.add("李四");
        //列表迭代器
        ListIterator<String> it = list.listIterator();
        while(it.hasNext()){
            String str =it.next();
            if("王五".equals(str)){
                it.add("孙七");//此方法,迭代器没有
            }
        }
        System.out.println(list);
    }
}

List系列集合中的两个删除的方法
1.直接删除元素(boolean remove(Object o))
2.通过索引进行删除(remove(int index))

4. ArrayList集合

java.util.ArrayList 集合数据存储的结构是可变数组结构。查询遍历元素的效率比较高,增删元素的效率比较低,由于日常开发中使用最多的功能为查询数据、遍历数据,所以ArrayList 是最常用的集合。
许多程序员开发时非常随意地使用ArrayList完成任何需求,并不严谨,这种用法是不提倡的
例:

public class CollectionTest {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("张三");
        list.add("王五");
        list.add("李四");
        //列表迭代器
        ListIterator<String> it = list.listIterator();
        while(it.hasNext()){
            String str =it.next();
            if("王五".equals(str)){
                it.add("孙七");//此方法,迭代器没有
            }
        }
        System.out.println(list);
    }
}

5. LinkedList集合

java.util.LinkedList 集合底层使用链表结构(链表的特点:有头有尾),查询遍历元素效率比较低,增删元素的效率比较高

常用方法:

方法名说明
boolean addFirst(E e)将指定元素插入列表开头
boolean addLast(E e)将指定元素添加到列表结尾
E getFirst()获取列表第一个元素
E getLast()获取列表最后一个元素
E removeFirst()移除并返回列表的第一个元素
E removeLast()移除并返回列表的最后一个元素
boolean isEmpty()如果列表中没有元素,返回true
E pop()从此列表所表示的堆栈处弹出一个元素

例:

public class CollectionTest {
    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<String>();
        list.add("李四");
        list.addLast("张三");
        list.addFirst("王五");

        System.out.println(list.getFirst());
        System.out.println(list.getLast());

        System.out.println(list.removeFirst());
        System.out.println(list.removeLast());

        while(!list.isEmpty()){
            System.out.println(list.pop());//弹出集合中栈顶元素
        }
    }
}

第四章 Set集合

1. Set集合

jSet 接口和List 接口一样,同样继承自Collection 接口,它与Collection 接口中的方法基本一致,并没有对Collection 接口进行功能上的扩充,只是比Collection 接口更加严格。

与List接口不同的是, Set 接口中元素无序,并且都会以某种规则保证存入的元素不出现重复,没有索引,不能使用普通for循环遍历
例:

public class CollectionTest {
    public static void main(String[] args) {
        Set<String> set = new TreeSet<String>();
        set.add("李四");
        set.add("张三");
        set.add("王五");
        set.add("李四");

        for (String s :set){
            System.out.println(s);
        }
    }
}

结果:

张三
李四
王五

2. HashSet集合

java.util.HashSet 是Set 接口的一个实现类,它所存储的元素是不可重复的,并且元素都是无序的(即存取顺序不一致)。
java.util.HashSet 底层的实现是哈希表结构(其实是java.util.HashMap 支持),最多只能存储一个null元素。
HashSet 是根据对象的哈希值来确定元素在集合中的存储位置,因此具有良好的存取和查找性能。保证元素唯一性的方式依赖于: hashCode 与equals 方法

例:

public class CollectionTest {
    public static void main(String[] args) {
        HashSet<String> set = new HashSet<String>();
        set.add("李四");
        set.add("张三");
        set.add("王五");
        set.add("李四");

        for (String s :set){
            System.out.println(s);
        }
    }
}

结果:

张三
李四
王五

3. TreeSet集合

TreeSet集合使用红黑树数据结构实现元素的排序和存储,底层实际上是一个TreeMap集合,放到TreeSet集合中的元素:有序且唯一,即不可重复,有序是指存储的元素会按照指定的规则自动排序
可以将元素按照规则进行排序
TreeSet():根据其元素的自然排序进行排序
TreeSet(Comparator comparator) :根据指定的比较器进行排序
例:

public class CollectionTest {
    public static void main(String[] args) {
        TreeSet<String> set = new TreeSet<String>();
        set.add("李四");
        set.add("张三");
        set.add("王五");
        set.add("李四");

        for (String s :set){
            System.out.println(s);
        }
    }
}
3.1 自然排序

实现步骤

  1. 使用空参构造创建TreeSet集合
    用TreeSet集合存储自定义对象,无参构造方法使用的是自然排序对元素进行排序的
  2. 自定义的Student类实现Comparable接口
    自然排序,就是让元素所属的类实现Comparable接口,重写compareTo(T o)方法
  3. 重写接口中的compareTo方法
    重写方法时,一定要注意排序规则必须按照要求的主要条件和次要条件来写

例:

public class Student extends Person implements Comparable<Student>{
    private int sex;//性别
    public Student(){

    }
    public Student(String name, int age, int sex) {
        super(name, age);
        this.sex = sex;
    }
    @Override
    public void eat(){
        System.out.println(super.getName()+"要吃饭!");
    }
    @Override
    public void work() {
        System.out.println("我要上学");
    }

    @Override
    public int compareTo(Student o) {
        int result = this.getAge() - o.getAge();
        return result==0?this.getName().compareTo(o.getName()):result;//不相等就比较姓名,否则就返回结果
    }
}
public class CollectionTest {
    public static void main(String[] args) {
        TreeSet<Student> set = new TreeSet<Student>();
        Student student = new Student("张三",23,1);
        Student student1 = new Student("李四",22,1);
        Student student2 = new Student("王五",29,1);
        Student student3 = new Student("陈六",20,1);
        set.add(student);
        set.add(student1);
        set.add(student2);
        set.add(student3);
        
        for (Student s :set){
            System.out.println(s);
        }
    }
}

结果:

Person{name='陈六', age=20}
Person{name='李四', age=22}
Person{name='张三', age=23}
Person{name='王五', age=29}
3.2 比较器排序

实现步骤

  • 用TreeSet集合存储自定义对象,带参构造方法使用的是比较器排序对元素进行排序
  • 比较器排序,就是让集合构造方法接收Comparator的实现类对象,重写compare(T o1,T o2) 方法
  • 重写方法时,一定要注意排序规则必须按照要求的主要条件和次要条件来写

例:

public class Student extends Person {
    private int sex;//性别
    public Student(){

    }
    public Student(String name, int age, int sex) {
        super(name, age);
        this.sex = sex;
    }
    @Override
    public void eat(){
        System.out.println(super.getName()+"要吃饭!");
    }
    @Override
    public void work() {
        System.out.println("我要上学");
    }
}

public class CollectionTest {
    public static void main(String[] args) {
        TreeSet<Student> set = new TreeSet<Student>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int result = o1.getAge() - o2.getAge();
                return result == 0?o1.getName().compareTo(o2.getName()):result;
            }
        });
        Student student = new Student("张三", 23, 1);
        Student student1 = new Student("李四", 22, 1);
        Student student2 = new Student("王五", 29, 1);
        Student student3 = new Student("陈六", 20, 1);
        set.add(student);
        set.add(student1);
        set.add(student2);
        set.add(student3);

        for (Student s : set) {
            System.out.println(s);
        }
    }
}

结果:
Person{name=‘陈六’, age=20}
Person{name=‘李四’, age=22}
Person{name=‘张三’, age=23}
Person{name=‘王五’, age=29}

3.3 两种排序的区别

排序

  • 自然排序: 自定义类实现Comparable接口,重写compareTo方法,根据返回值进行排序
  • 比较器排序: 创建TreeSet对象的时候传递Comparator的实现类对象,重写compare方法,根据返回值进行排序
  • 在使用的时候,默认使用自然排序,当自然排序不满足现在的需求时,必须使用比较器排序

返回值的规则

  • 如果返回值为负数,表示当前存入的元素是较小值,存左边
  • 如果返回值为0,表示当前存入的元素跟集合中元素重复了,不存
  • 如果返回值为正数,表示当前存入的元素是较大值,存右边

第五章 Map集合

1. Map概述

Map 中的集合不能包含重复的键,值可以重复;每个键只能对应一个值
如:身份证–姓名(key–value),身份证不可重复,姓名可重复
基本上都需要重写键的的hashCode()方法、equals()方法

2. 常用方法

方法名说明
public V put(K key, V value)把指定的键与指定的值添加到Map集合中。
public V remove(Object key)把指定的键 所对应的键值对元素 在Map集合中删除,返回被删除元素的值
public V get(Object key)根据指定的键,在Map集合中获取对应的值
public Set keySet()获取Map集合中所有的键,存储到Set集合中
public Set<Map.Entry<K,V>> entrySet()获取到Map集合中所有的键值对对象的集合(Set集合)

例:
需要提前重写自定义类的hashCode()方法、equals()方法

import java.util.Objects;

public class Student extends Person {
    private int sex;//性别
    public Student(){

    }
    public Student(String name, int age, int sex) {
        super(name, age);
        this.sex = sex;
    }
    @Override
    public void eat(){
        System.out.println(super.getName()+"要吃饭!");
    }
    @Override
    public void work() {
        System.out.println("我要上学");
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Student)) return false;
        Student student = (Student) o;
        if(getAge()!= student.getAge())
            return false;
        return getName()!= null?getName().equals(student.getName()):student.getName() == null;
    }

    @Override
    public int hashCode() {
        int result = getName() != null ? getName().hashCode() : 0;
        result = 31 * result + getAge();
        return result;
    }
}
public class CollectionTest {
    public static void main(String[] args) {
        //创建Map对象
        HashMap<Student,Integer> map = new HashMap<Student,Integer>();
        //新增元素
        Student student = new Student("张三", 23, 1);
        Student student1 = new Student("李四", 22, 1);
        Student student2 = new Student("王五", 29, 1);
        Student student3 = new Student("陈六", 20, 1);
        Student student4 = new Student("李四", 22, 1);
        //将元素添加进集合
        map.put(student,1);
        map.put(student1,2);
        map.put(student2,3);
        map.put(student3,4);
        map.put(student4,5);
        System.out.println(map);
        if(map.containsValue(5)){//if有值为5就删除student4
            map.remove(student4);            
        }
        System.out.println(map);
        System.out.println(map.get(4));
        System.out.println(map.get(student3));
        
        //for循环遍历1
        //获取键集合(把单个键取出来,存入集合)
        Set<Student> keys = map.keySet();
        //遍历键集合
        for(Student key:keys){
            System.out.println(key+"的值是: "+map.get(key));
        }
        
        //for循环遍历2
        //获取所有entry对象集entrySet(把一行行键值当成一个个对象取出,存入集合)
        Set<Map.Entry<Student, Integer>> entries= map.entrySet();
        //遍历每个entry对象
        for(Map.Entry<Student, Integer> entry:entries){
            System.out.println(entry.getKey()+"的值是: "+entry.getValue());
        }
        
        //foreach遍历
        map.forEach((Student key,Integer value)->{
            System.out.println(key+" : "+value);
        });
    }
}

结果:

{Person{name='张三', age=23}=1, Person{name='陈六', age=20}=4, Person{name='李四', age=22}=5, Person{name='王五', age=29}=3}
{Person{name='张三', age=23}=1, Person{name='陈六', age=20}=4, Person{name='王五', age=29}=3}
null
4
Person{name='张三', age=23}的值是: 1
Person{name='陈六', age=20}的值是: 4
Person{name='王五', age=29}的值是: 3
Person{name='张三', age=23}的值是: 1
Person{name='陈六', age=20}的值是: 4
Person{name='王五', age=29}的值是: 3
Person{name='张三', age=23} : 1
Person{name='陈六', age=20} : 4
Person{name='王五', age=29} : 3
  • 使用put方法时,若指定的键(key)在集合中没有,则没有这个键对应的值,返回null,并把指定的键值添加到集合中
  • 若指定的键(key)在集合中存在,则返回值为集合中键对应的值(该值为替换前的值),并把指定键所对应的值,替换成指定的新值

3. Map常用子类

HashMap:存储数据采用的哈希表结构,元素的存取顺序不能保证一致。由于要保证键的唯一、不重复,需要重写键的hashCode()方法、equals()方法
例:不重写

public class CollectionTest {
    public static void main(String[] args) {
        HashMap<Student,Integer> map = new HashMap<Student,Integer>();
        Student student = new Student("张三", 23, 1);
        Student student1 = new Student("李四", 22, 1);
        Student student2 = new Student("王五", 29, 1);
        Student student3 = new Student("陈六", 20, 1);
        Student student4 = new Student("李四", 22, 1);
        map.put(student,1);
        map.put(student1,2);
        map.put(student2,3);
        map.put(student3,4);
        map.put(student4,5);

        map.forEach((Student key,Integer value)->{
            System.out.println(key+" : "+value);
        });
    }
}

结果:

Person{name='陈六', age=20} : 4
Person{name='王五', age=29} : 3
Person{name='李四', age=22} : 2
Person{name='李四', age=22} : 5
Person{name='张三', age=23} : 1

例:重写:

import java.util.Objects;

public class Student extends Person {
    private int sex;//性别
    public Student(){

    }
    public Student(String name, int age, int sex) {
        super(name, age);
        this.sex = sex;
    }
    @Override
    public void eat(){
        System.out.println(super.getName()+"要吃饭!");
    }
    @Override
    public void work() {
        System.out.println("我要上学");
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Student)) return false;
        Student student = (Student) o;
        if(getAge()!= student.getAge())
            return false;
        return getName()!= null?getName().equals(student.getName()):student.getName() == null;
    }

    @Override
    public int hashCode() {
        int result = getName() != null ? getName().hashCode() : 0;
        result = 31 * result + getAge();
        return result;
    }
}

public class CollectionTest {
    public static void main(String[] args) {
        HashMap<Student,Integer> map = new HashMap<Student,Integer>();
        Student student = new Student("张三", 23, 1);
        Student student1 = new Student("李四", 22, 1);
        Student student2 = new Student("王五", 29, 1);
        Student student3 = new Student("陈六", 20, 1);
        Student student4 = new Student("李四", 22, 1);
        map.put(student,1);
        map.put(student1,2);
        map.put(student2,3);
        map.put(student3,4);
        map.put(student4,5);

        map.forEach((Student key,Integer value)->{
            System.out.println(key+" : "+value);
        });
    }
}

结果:

Person{name='张三', age=23} : 1
Person{name='陈六', age=20} : 4
Person{name='李四', age=22} : 5
Person{name='王五', age=29} : 3

LinkedHashMap:HashMap下有个子类LinkedHashMap,存储数据采用的哈希表结构+链表结构。通过链表结构可以保证元素的存取顺序一致;通过哈希表结构可以保证的键的唯一、不重复,需要重写键的hashCode()方法、equals()方法
例:同上

TreeMap:TreeMap底层是红黑树结构,依赖自然排序或者比较器排序,对键进行排序,如果键存储的是自定义对象,需要实现Comparable接口或者在创建TreeMap对象时候给出比较器排序规则
例:

    public static void main(String[] args) {
        TreeMap<Student,Integer> map = new TreeMap<Student,Integer>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int result = o1.getAge() - o2.getAge();
                return result == 0?o1.getName().compareTo(o2.getName()):result;
            }
        });
        Student student = new Student("张三", 23, 1);
        Student student1 = new Student("李四", 22, 1);
        Student student2 = new Student("王五", 29, 1);
        Student student3 = new Student("陈六", 20, 1);
        Student student4 = new Student("李四", 22, 1);
        map.put(student,1);
        map.put(student1,2);
        map.put(student2,3);
        map.put(student3,4);
        map.put(student4,5);

        map.forEach((Student key,Integer value)->{
            System.out.println(key+" : "+value);
        });
    }

结果:

Person{name='陈六', age=20} : 4
Person{name='李四', age=22} : 5
Person{name='张三', age=23} : 1
Person{name='王五', age=29} : 3

Map接口中的集合都有两个泛型变量,在使用时,要为两个泛型变量赋予数据类型。两个泛型变量的数据类型可以相同,也可以不同

第六章 常用库

1. Object

  • java.lang.Object 类是Java语言中的根类,即所有类的父类
  • 它中描述的所有方法子类都可以使用。在对象实例化的时候,最终找的父类就是Object
  • 如果一个类没有特别指定父类, 那么默认则继承自Object类

常用方法

方法名说明
public String toString()返回该对象的字符串表示
public boolean equals(Object obj)指示其他某个对象是否与此对象“相等”
int hashCode()返回该对象的哈希码值。
void notify()唤醒在此对象监视器上等待的单个线程
void wait()在其他线程调用此对象的 notify() 方法或 notifyAll() 方法前,导致当前线程等待
Class<?> getClass()返回此 Object 的运行时类

反射常用最后一个,多线程常用45,集合常用23,一般常用1
例:

import java.util.Objects;

public class Student extends Person {
    private int sex;//性别
    public Student(){

    }
    public Student(String name, int age, int sex) {
        super(name, age);
        this.sex = sex;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Student)) return false;
        Student student = (Student) o;
        if(getAge()!= student.getAge())
            return false;
        return getName()!= null?getName().equals(student.getName()):student.getName() == null;
    }

    @Override
    public int hashCode() {
        int result = getName() != null ? getName().hashCode() : 0;
        result = 31 * result + getAge();
        return result;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sex=" + sex +
                "} " + super.toString();
    }
}

java.util.Objects 类
Object的equals方法容易抛出空指针异常,而Objects类中的equals方法就优
化了这个问题。方法如下:

  • public static boolean equals(Object a, Object b):判断两个对象是否相等

源码如下:

public static boolean equals(Object a, Object b) {  
return (a == b) || (a != null && a.equals(b));  
}

2. 日期时间类

2.1 Date类

java.util.Date 类 表示特定的瞬间,精确到毫秒

方法说明
public Date()分配Date对象并初始化此对象,以表示分配它的时间(精确到毫秒)
public Date(long date)分配Date对象并初始化此对象,以表示自从标准基准时间(称为“历元(epoch)”,即1970年1月1日00:00:00 GMT)以来的指定毫秒数
public long getTime()把日期对象转换成对应的时间毫秒值

简单来说:使用无参构造,可以自动设置当前系统时间的毫秒时刻;指定long类型的构造参数,可以自定义毫秒时刻
例:

public static void main(String[] args) {
        //无参构造器
        Date date = new Date();
        System.out.println(date);//Tue Sep 17 16:05:52 CST 2024
        //有参构造器
        Date date1 = new Date(0L);
        System.out.println(date1);//Thu Jan 01 08:00:00 CST 1970
        //获取date日期的毫秒值
        System.out.println(date.getTime());//1726560352988
    }
2.2 DateFormat类

java.text.DateFormat 是日期/时间格式化子类的抽象类,我们通过这个类可以帮我们完成日期和文本之间的转换,也就是可以在Date对象与String对象之间进行来回转换

格式化:按照指定的格式,从Date对象转换为String对象
解析:按照指定的格式,从String对象转换为Date对象

构造方法
由于DateFormat为抽象类,不能直接使用,常用的子类有java.text.SimpleDateFormat 这个类需要一个模式(格式)来指定格式化或解析的标准。构造方法为:

格式规则

public SimpleDateFormat(String pattern):用给定的模式和默认语言环境的日期格式符号
构造SimpleDateFormat

参数pattern是一个字符串,代表日期时间的自定义格式

常用的格式规则为:

标识字母(区分大小写)含义
y
M
d
H
m
s

例:

public static void main(String[] args) throws ParseException {
        //无参构造器
        Date date = new Date();
        System.out.println(date);//Tue Sep 17 16:19:31 CST 2024
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(format.format(date));//2024-09-17 16:19:31//Data转字符串
        System.out.println(format.parse(format.format(date)));//Tue Sep 17 16:19:31 CST 2024//字符串转Date
    }
2.3 Calendar类

java.util.Calendar 是日历类,在Date后出现,替换掉了许多Date的方法。该类将所有可能用到的时间信息封装为静态成员变量,方便获取。日历类就是方便获取各个时间属性
常用方法

方法名说明
public static Calendar getInstance()使用默认时区和语言环境获得一个日历
public int get(int field)返回给定日历字段的值。
public void set(int field, int value)将给定的日历字段设置为给定值。
public abstract void add(int field, int amount)根据日历的规则,为给定的日历字段添加或减去指定的时间量。
public Date getTime()返回一个表示此Calendar时间值(从历元到现在的毫秒偏移量)的Date对象

Calendar类中提供很多成员常量,代表给定的日历字段:

字段值含义
YEAR
MONTH月(从0开始,可以+1使用)
DAY_OF_MONTH月中的天(几号)
HOUR时(12小时制)
HOUR_OF_DAY时(24小时制)
MINUTE
SECOND
DAY_OF_WEEK周中的天(周几,周日为1,可以-1使用)

例:

public static void main(String[] args)  {
                // 创建Calendar对象
                Calendar cal = Calendar.getInstance();
                // 获取年
                int year = cal.get(Calendar.YEAR);
                // 设置月
                // 获取月
                int month = cal.get(Calendar.MONTH)+1;
                cal.set(Calendar.MONTH,3);
                int month1 = cal.get(Calendar.MONTH)+1;
                // 获取日
                int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
                System.out.println(year + "年" + month + "月" + dayOfMonth + "日");
                System.out.println(year + "年" + month1 + "月" + dayOfMonth + "日");

                cal.add(Calendar.DAY_OF_MONTH, 2); // 加2天
                cal.add(Calendar.YEAR, -3); // 减3年
                int day = cal.get(Calendar.DAY_OF_MONTH);
                int year1 = cal.get(Calendar.YEAR);

                System.out.println(year1 + "年" + month + "月" + day + "日");
                System.out.println(cal.getTime());
            }

结果:

202491720244172021919Mon Apr 19 16:46:33 CST 2021

西方星期的开始为周日,中国为周一
在Calendar类中,月份的表示是以0-11代表1-12月
日期是有大小关系的,时间靠后,时间越大

3. System类

java.lang.System 类中提供了大量的静态方法,可以获取与系统相关的信息或系统级操作
常用的方法

方法名说明
public static long currentTimeMillis()返回以毫秒为单位的当前时间
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)将数组中指定的数据拷贝到另一个数组中
  • currentTimeMillis方法就是 获取当前系统时间与1970年01月01日00:00点之间的毫秒差值
  • 数组的拷贝动作是系统级的,性能很高。System.arraycopy方法具有5个参数,含义分别为源数组,源数组索引起始位置,目标数组,目标数组索引起始位置,复制元素个数

例:

public static void main(String[] args)  {
        System.out.println(System.currentTimeMillis());//打印当前时间的毫秒值
        int[] src = new int[]{1,2,3,4};
        int[] desc = new int[]{5,6,7,8};
        System.arraycopy(src,1,desc,1,2);
        for(int i :src){
            System.out.print("src:"+i+" ");
        }
        for(int i :desc){
            System.out.print("desc:"+i+" ");
        }

    }

结果:

1726563432465
src:1 src:2 src:3 src:4 desc:5 desc:2 desc:3 desc:8 

4. String类

java.lang.String 类代表字符串

4.1 特点
  • 字符串不变:字符串的值在创建后不能被更改
  • 因为String对象是不可变的,所以它们可以被共享
  • “abc” 等效于 char[] data={ ‘a’ , ‘b’ , ‘c’ }, String底层是靠字符数组实现的

4.2 常用方法

方法名说明
public String()初始化新创建的 String对象,以使其表示空字符序列
public String(char[] value)通过当前参数中的字符数组来构造新的String
public String(byte[] bytes)通过使用平台的默认字符集解码当前参数中的字节数组来构造新的String
public boolean equals (Object anObject)将此字符串与指定对象进行比较
public boolean equalsIgnoreCase (String anotherString)将此字符串与指定对象进行比较,忽略大小写
public int length ()返回此字符串的长度
public String concat (String str)将指定的字符串连接到该字符串的末尾。
public char charAt (int index)返回指定索引处的 char值。
public int indexOf (String str)返回指定子字符串第一次出现在该字符串内的索引。
public String substring (int beginIndex)返回一个子字符串,从beginIndex开始截取字符串到字符串结尾
public String substring (int beginIndex, int endIndex)返回一个子字符串,从beginIndex到endIndex截取字符串。含beginIndex,不含endIndex
public char[] toCharArray ()将此字符串转换为新的字符数组
public byte[] getBytes ()使用平台的默认字符集将该 String编码转换为新的字节数组
public String replace (CharSequence target, CharSequence replacement)将与target匹配的字符串使用replacement字符串替换
public String[] split(String regex)将此字符串按照给定的regex(规则)拆分为字符串数组
isEmpty()用于判断字符串是否为空
trim()用于删除字符串的头尾空白符
  • String 中 == 比较引用地址是否相同,equals() 比较字符串的内容是否相同
  • String类是final的,它的所有成员变量也都是final的。为什么是final的?
    • 线程安全:同一个字符串实例可以被多个线程共享,因为字符串不可变,本身就是线程安全
    • 支持hash映射和缓存:因为String的hash值经常会使用到,比如作为 Map 的键,不可变的特性使得 hash 值也不会变,不需要重新计算
    • 字符串常量池优化:String对象创建之后,会缓存到字符串常量池中,下次需要创建同样的对象时,可以直接返回缓存的引用

5. StringBuilder类

StringBuilder又称为可变字符序列,它是一个类似于 String 的字符串缓冲区,通过某些方法调用可以改变该序列的长度和内容。StringBuilder是个字符串的缓冲区,即它是一个容器,容器中可以装很多字符串。并且能够对其中的字符串进行各种操作,线程不安全StringBuffer用于多线程是安全
常用方法

方法名说明
public StringBuilder()构造一个空的StringBuilder容器
public StringBuilder(String str)构造一个StringBuilder容器,并将字符串添加进去
public StringBuilder append(…)添加任意类型数据的字符串形式,并返回当前对象自身
public String toString()将当前StringBuilder对象转换为String对象
public static void main(String[] args)  {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("你好,");
        stringBuilder.append("007");
        System.out.println(stringBuilder.toString());
    }

结果:

你好,007

6. Math类

java.lang.Math 类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数。类似这样的工具类,其所有方法均为静态方法,并且不会创建对象,调用起来非常简单
常用方法

方法名说明
public static double abs(double a)返回 double 值的绝对值
public static double ceil(double a)返回大于等于参数的最小的整数
public static double floor(double a)返回小于等于参数最大的整数
public static long round(double a)返回最接近参数的 long。(相当于四舍五入方法)

例:

public static void main(String[] args)  {
        double d1 = Math.abs(-6);
        double d2 = Math.ceil(-6.6);
        double d3 = Math.floor(-6.6);
        double d4 = Math.round(-6.6);
        System.out.println(d1);
        System.out.println(d2);
        System.out.println(d3);
        System.out.println(d4);
    }

结果:

6.0
-6.0
-7.0
-7.0

7. Arrays类

java.util.Arrays 类包含用来操作数组的各种方法,比如排序和搜索等。其所有方法均为静态方法,调用起来非常简单
常用方法

方法名说明
public static String toString(int[] a)返回指定数组内容的字符串表示形式
public static void sort(int[] a)对指定的 int 型数组按数字升序进行排序

例:

public static void main(String[] args)  {
        int[] src = new int[]{1,2,3,4};
        int[] desc = new int[]{5,6,7,8,3,21,23,11};
        System.out.println(src);
        System.out.println(Arrays.toString(src));
        System.out.println("排序前:"+Arrays.toString(desc));
        Arrays.sort(desc);
        System.out.println("排序后:"+Arrays.toString(desc));
    }

结果:

[I@6b884d57
[1, 2, 3, 4]
排序前:[5, 6, 7, 8, 3, 21, 23, 11]
排序后:[3, 5, 6, 7, 8, 11, 21, 23]

手出汗

太充实了!!!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2142951.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

kubeadm方式安装k8s+基础命令的使用

一、安装环境 二、前期准备 1.设置免密登录 [rootk8s-master ~]# ssh-keygen [rootk8s-master ~]# ssh-copy-id root192.168.2.77 [rootk8s-master ~]# ssh-copy-id root192.168.2.88 2.yum源配置 3.清空创建缓存 4.主机映射&#xff08;三台主机都要设置&#xff09; 5.安装…

vivado中选中bd文件后generate output product是什么用,create HDL wrapper是什么用

vivado中选中bd文件后generate output product是什么用 在Vivado中&#xff0c;“Generate Output Products” 是一个重要的步骤&#xff0c;它用于生成IP核的输出产品&#xff0c;这些产品是将IP核集成到设计中所需的文件。这些输出产品包括&#xff1a; 综合文件&#xff…

多线程下的共享变量访问数据竞争的问题

多线程下对共享变量的写存在数据竞问题可导致数据与预期不一致。最近在研究race conditions漏洞&#xff0c;用以下python 代码记录一下&#xff0c;以此论证&#xff0c;如下&#xff1a; from concurrent.futures import ThreadPoolExecutor globalNum 5 def test():global…

微积分-反函数6.1(反函数)

表1提供了一项实验的数据&#xff0c;其中细菌培养物在有限营养基中以100个细菌开始&#xff1b;在定时记录下细菌数量随时间的变化。细菌数量 N N N 是时间 t t t 的函数&#xff1a; N f ( t ) N f(t) Nf(t)。 然而&#xff0c;假设生物学家改变了她的观点&#xff0c;开…

京东App秒级百G日志传输存储架构设计与实战

本文作者&#xff1a;平台业务研发部-武伟峰&#xff0c;数据与智能部-李阳 背景 在日常工作中&#xff0c;我们通常需要存储一些日志&#xff0c;譬如用户请求的出入参、系统运行时打印的一些info、error之类的日志&#xff0c;从而对系统在运行时出现的问题有排查的依据。 …

作为研发部门的负责人,如何助力产品在市场竞争中胜出?浅谈 CTQ

在激烈的市场竞争中&#xff0c;产品研发团队如何帮助企业的产品脱颖而出&#xff1f;成功的产品往往不仅依赖于强大的功能和技术创新&#xff0c;还需要通过高效的研发效能&#xff0c;包括效率、质量和创新&#xff0c;来提升产品的市场竞争力。在本文中&#xff0c;我们将探…

文档内容识别系统源码分享

文档内容识别检测系统源码分享 [一条龙教学YOLOV8标注好的数据集一键训练_70全套改进创新点发刊_Web前端展示] 1.研究背景与意义 项目参考AAAI Association for the Advancement of Artificial Intelligence 项目来源AACV Association for the Advancement of Computer Vis…

一款源码阅读的插件

文章目录 进度汇报功能预览添加高亮标记高亮风格设置笔记颜色设置数据概览高亮数据详情 结尾 进度汇报 之前提到最近有在开发一个源码阅读的IDEA插件&#xff0c;第一版已经开发完上传插件市场了&#xff0c;等官方审批通过就可以尝鲜了。插件名称&#xff1a;Mark source cod…

基于STM32F407ZGT6——看门狗

独立看门狗 独立看门狗的时钟由独立的RC 振荡器LSI 提供&#xff0c;即使主时钟发生故障它仍然有效&#xff0c;非常独立。 LSI 的频率一般在30~60KHZ 之间&#xff0c;根据温度和工作场合会有一定的漂移&#xff0c; 所以独立看门狗的定时时间并不一定非常精确&#xff0c;只适…

格式化u盘选择FAT还是NTFS U盘和硬盘格式化两者选谁

Mac用户在将U盘或硬盘进行格式化时&#xff0c;选择FAT还是NTFS往往是一个让人纠结的问题。很多用户不知道这两个格式之间有什么区别&#xff0c;更不知道在格式化时如何做出选择。本文将为大家介绍Mac选择FAT还是NTFS&#xff0c;并为大家推荐U盘和硬盘格式化两者选谁。 一、…

36.贪心算法3

1.坏了的计算器&#xff08;medium&#xff09; . - 力扣&#xff08;LeetCode&#xff09; 题目解析 算法原理 代码 class Solution {public int brokenCalc(int startValue, int target) {// 正难则反 贪⼼int ret 0;while (target > startValue) {if (target % 2 0…

第159天:安全开发-Python-协议库爆破FTPSSHRedisSMTPMYSQL等

案例一: Python-文件传输爆破-ftplib 库操作 ftp 协议 开一个ftp 利用ftp正确登录与失败登录都会有不同的回显 使用ftplib库进行测试 from ftplib import FTP # FTP服务器地址 ftp_server 192.168.172.132 # FTP服务器端口&#xff08;默认为21&#xff09; ftp_po…

Base 社区见面会 | 新加坡站

活动信息 备受期待的 Base 社区见面会将于 Token2049 期间在新加坡举行&#xff0c;为 Base 爱好者和生态系统建设者提供一个独特的交流机会。本次活动由 DAOBase 组织&#xff0c;Base 和 Coinbase 提供支持&#xff0c;并得到了以下合作伙伴的大力支持&#xff1a; The Sand…

Python 课程15-PyTorch

前言 PyTorch 是一个开源的深度学习框架&#xff0c;由 Facebook 开发&#xff0c;广泛应用于学术研究和工业领域。与 TensorFlow 类似&#xff0c;PyTorch 提供了强大的工具用于构建和训练深度学习模型。PyTorch 的动态计算图和灵活的 API 使得它特别适合研究和实验。它还支持…

GetMaterialApp组件的用法

文章目录 1. 知识回顾2. 使用方法2.1 源码分析2.2 常用属性 3. 示例代码4. 内容总结 我们在上一章回中介绍了"Get包简介"相关的内容&#xff0c;本章回中将介绍GetMaterialApp组件.闲话休提&#xff0c;让我们一起Talk Flutter吧。 1. 知识回顾 我们在上一章回中已经…

King3399 SDK编译简明教程

该文章仅供参考&#xff0c;编写人不对任何实验设备、人员及测量结果负责&#xff01;&#xff01;&#xff01; 0 引言 文章主要介绍King3399&#xff08;瑞芯微rk3399开发板&#xff0c;荣品&#xff09;官方SDK编译过程&#xff0c;涉及环境配置、补丁以及编译过程中注意事…

Using OpenAI API from Firebase Cloud Functions in flutter app

题意&#xff1a;“在 Flutter 应用中通过 Firebase Cloud Functions 使用 OpenAI API。” 问题背景&#xff1a; I cant figure out how to make this work. “我不知道该如何让这正常运行。” This is my cloud function in Javascript. Im trying a simple code to see if…

鸿蒙媒体开发系列04——音频播放

如果你也对鸿蒙开发感兴趣&#xff0c;加入“Harmony自习室”吧&#xff01;扫描下方名片&#xff0c;关注公众号&#xff0c;公众号更新更快&#xff0c;同时也有更多学习资料和技术讨论群。 1、如何选择音频播放开发方式 在HarmonyOS系统中&#xff0c;多种API都提供了音频播…

C++_map_set详解

关联容器的基本介绍 关联容器支持高效的关键字查找和访问。map和set是最主要关联容器。关联容器也是用来存储数据的&#xff0c;与序列式容器不同的是&#xff0c;其里面存储的是<key, value>结构的键值对&#xff0c;在数据检索时比序列式容器效率更高。C标准库中提供了…

如何关闭前端Chrome的debugger反调试

1、禁用浏览器断点 2. 把控制台独立一个窗口