我是靠谱客的博主 大气树叶,最近开发中收集的这篇文章主要介绍Java集合&常用类集合ListSetMap常用类,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

文章目录

  • 集合
    • 集合结构图
    • 集合概念
      • Collection
      • Collection接口常用方法
  • List
    • ArrayList类
      • 特点
    • Vector
    • LinkedList类
    • List特点
      • 创建List
      • 遍历List
      • List和Array转换
  • Set
    • HashSet
    • TreeSet
  • Map
    • Map中的常用方法
    • HashMap
    • TreeMap
  • 常用类
    • Object类
      • 类中方法
    • String类
      • 创建字符串
      • 字符串比较
      • 字符串长度
      • 连接字符串
      • 操作子串
      • 字符串方法
    • StringBuilder和StringBuffer类
      • StringBuffer方法
    • System类
      • arraycopy()方法
      • currentTimeMillis()方法
      • gc()方法
      • exit(int status)方法
    • Date日期类
      • 基本概念
      • Date
      • LocalDateTime
      • ZonedDateTime
      • DateTimeFormatter
      • 日期时间字符串转换

集合

集合结构图

在这里插入图片描述

集合概念

  • 在计算机中引入集合是为了便于处理一组类似的数据,例如:

    • 计算所有同学的总成绩和平均成绩
    • 列举所有商品名称和价格

    在Java中,如果一个对象可以在内部持有若干其他Java对象,并对外提供访问接口,这种对象就被成为集合。数组可以看作是一个集合

    //可以持有10个String对象
    String[] string = new String[10];
    //可以放入String对象
    string[0] = "hello";
    //获取String对象
    String hello = string[0];
    

    但数组有如下限制:

    • 数组初始化后大小不可变
    • 数组只能按索引顺序存取

    因此需要各种不同类型的集合类来处理不同的数据,例如:

    • 可变大小的顺序链表
    • 保证无重复元素的集合

Collection

  • Java标准库自带的java.util包提供了集合类:Collection,它是除Map外的其他类的根接口。java.util包下主要提供了三种类型的集合:

    • List:一种有序可重复列表的集合,例如,按索引排列的Student的List;
    • Set:一种保证无序没有重复元素的集合,例如,所有无重复名称的Student的List;
    • Map:一种通过键/值查找的映射表集合,例如,根据Student的name查找对象Student的Map。
  • Java集合接口的特点:

    1. 实现了接口和实现类相分离,例如,有序表的接口是List,具体的实现类有ArrayList,LinkedList等

    2. 支持泛型,可以限制在一个集合中只能放入同一种类型的元素,例如:

      List<String> list = new ArrayList<>();//只能放String类型
    
  • Java访问集合总是通过统一的方式:迭代器(Iterator)来实现,好处在于无需知道集合内部元素是按什么方式存储的。

  • 不应该继续使用的遗留类:

    • Hashtable:一种线程安全的Map实现
    • Vector:一种线程安全的List实现
    • Stack:基于Vector实现的LIFO的栈
  • 不该使用的遗留接口:

    • Enumberation:已被Iterator< E >取代

Collection接口常用方法

方法名称说明
boolean add(E e)向集合中添加一个元素,如果集合对象被添加操作改变了,则返回 true。E 是元素的数据类型
boolean addAll(Collection c)向集合中添加集合 c 中的所有元素,如果集合对象被添加操作改变了,则返回 true。
void clear()清除集合中的所有元素,将集合长度变为 0。
boolean contains(Object o)判断集合中是否存在指定元素
boolean containsAll(Collection c)判断集合中是否包含集合 c 中的所有元素
boolean isEmpty()判断集合是否为空,是空则返回true
Iteratoriterator()返回一个 Iterator 对象,用于遍历集合中的元素
boolean remove(Object o)从集合中删除一个指定元素,当集合中包含了一个或多个元素 o 时,该方法只删除第一个符合条件的元素,该方法将返回 true。
boolean removeAll(Collection c)从集合中删除所有在集合 c 中出现的元素(相当于把调用该方法的集合减去集合 c)。如果该操作改变了调用该方法的集合,则该方法返回 true。
boolean retainAll(Collection c)从集合中删除集合 c 里不包含的元素(相当于把调用该方法的集合变成该集合和集合 c 的交集),如果该操作改变了调用该方法的集合,则该方法返回 true。
int size()返回集合中元素的个数
Object[] toArray()把集合转换为一个数组,所有的集合元素变成对应的数组元素。

List

  • List接口也是一个顶层接口,它继承了Collection接口,同时也是ArrayList、LinkedList等集合元素的父类
  • 在集合类中,List是一种有序列表,List行为几乎与数组相同,List内部按照放入元素的先后顺序存放,每个元素可以通过索引确定自己的位置,List的索引和数组一样从0开始。

ArrayList类

ArrayList是实现了List接口的**可扩容数组(动态数组)**,他的内部是基于数组实现的,具体定义如下:

public class ArrayList<E> extends AbstractList<E> implements List<E>,
RandomAccess,Cloneable,java.io.Serializable {...}
  • ArrayList可以实现所有可选择的列表操作,允许所有的元素,包括空值。ArrayList还提供了内部存储Iist的方法,它能够完全替代Vector,只有一点例外,ArrayList不是线程安全的容器。
  • ArrayList有一个容量的概念,这个数组的容量就是List用来存储元素的容量。
  • ArrayList不是线程安全的容器,如果多个线程中至少有两个线程修改了ArrayList的结构的话就会导致线程安全问题,作为替代条件可以使用线程安全的List,应使用Collections.synchronizedList
List list = Collections.synchronizedList(new Array(...));
  • ArrayList具有fail-fast快速失败机制,能够对ArrayList作出失败检测。当迭代集合的过程中该集合在结构上发生改变的时候,就有可能,会发生fail-fast,即抛出ConcurrentModificationException异常

特点

  • ArrayList实现了可变数组的大小,存储在内的数据成为元素,提供了基于索引的快速访问元素的方式,对尾部成员的增加和删除支持较好。
  • 使用 ArrayList 创建的集合,允许对集合中的元素进行快速的随机访问,不过,向 ArrayList 中插入与删除元素的速度相对较慢。
  • ArrayList 类的常用构造方法有如下两种重载形式:
    • ArrayList():构造一个初始容量为 10 的空列表。
    • ArrayList(Collection<? extends E> c):构造一个包含指定 Collection 元素的列表,这些元素是按照该 Collection 的迭代器返回它们的顺序排列的。
ArrayList arrayList = new ArrayList();

ArrayList temp = new ArrayList(arrayList);
  • ArrayList类除包含Collection接口中的方法之外,还包括List接口中提供的方法:
方法名称说明
E get(int index)获取此集合中指定索引位置的元素,E 为集合中元素的数据类型
int index(Object o)返回此集合中第一次出现指定元素的索引,如果此集合不包含该元 素,则返回 -1
int lastIndexOf(Object o)返回此集合中最后一次出现指定元素的索引,如果此集合不包含该 元素,则返回 -1
E set(int index, Eelement)将此集合中指定索引位置的元素修改为 element 参数指定的对象。 此方法返回此集合中指定索引位置的原元素
List subList(int fromlndex, int tolndex)返回一个新的集合,新集合中包含 fromlndex 和 tolndex 索引之间的所有元素。包含 fromlndex 处的元素,不包含 tolndex 索引处的元素
public class ArrayList_1 {

    public static void main(String[] args) {
        @SuppressWarnings({"all"})
        ArrayList arrayList = new ArrayList();
        //允许重复元素,允许添加null
        arrayList.add("12");
        arrayList.add("12");
        arrayList.add("zcz");
        arrayList.add(null);
        //[12, 12, zcz, null]
        System.out.println(arrayList);
        //get(int index)获取元素
        String a = (String)arrayList.get(0);//12
        System.out.println(a);
        //返回一次出现12的索引
        System.out.println(arrayList.indexOf("12"));//0
        //set修改指定索引位置的元素,返回原元素
        arrayList.set(1,10);
        System.out.println(arrayList);//[12, 10, zcz, null]

        //返回新集合,包含arrayList中0~2索引的元素
        List list = arrayList.subList(0,2);
        System.out.println(list);//[12, 10]
    }

}

Vector

  • Vector同ArrayList一样,都是基于数组实现的,只不过Vector是一个线程安全的容器,它对内部的每个方法都简单粗暴的上锁,避免多线程引起的安全性问题,但是通常这种同步方式需要的开销比较大,因此,访问元素的效率要远远低于ArrayList。
  • 还有一点在于扩容上,ArrayList扩容后的数组长度会增加50%,而Vector的扩容长度后数组会增加一倍。

LinkedList类

LinkedList是一个双向链表,允许存储任何元素(包括nul)。它的主要特性如下:

  • LinkedList所有的操作都可以表现为双向性的,索引到链表的操作将遍历从头到尾,视哪个距离近为遍历顺序。
  • ·注意这个实现也不是线程安全的,如果多个线程并发访问链表,并且至少其中的一个线程修改了链表的结构,那么这个链表必须进行外部加锁。或者使用
 List list = Collections.synchronizedList(new LinkedList(...));
  • LinkedList 类采用链表结构保存对象,这种结构的优点是便于向集合中插入或者删除元素。需要频繁向集合中插入和删除元素时,使用 LinkedList 类比 ArrayList 类效果高,但是 LinkedList 类随机访问元素的速度则相对较慢。这里的随机访问是指检索集合中特定索引位置的元素。
  • LinkedList除Collection和List接口外的方法
方法名称说明
void addFirst(E e)将指定元素添加到此集合的开头
void addLast(E e)将指定元素添加到此集合的末尾
E getFirst()返回此集合的第一个元素
E getLast()返回此集合的最后一个元素
E removeFirst()删除此集合中的第一个元素
E removeLast()删除此集合中的最后一个元素
public class LinkedList_ {

    public static void main(String[] args) {
        Person wang = new Person("wang",23);
        Person zhang = new Person("zhang",20);
        Person yao = new Person("yao",48);

        LinkedList linkedList = new LinkedList();
        linkedList.add(wang);
        linkedList.add(zhang);
        linkedList.add(yao);

        //添加对象到LinkedList集合中,toString方法输入对象信息
        System.out.println(linkedList);
        //添加元素到集合开头
        Person li = new Person("li",12);
        linkedList.addFirst(li);
        //添加元素到集合末尾
        Person zhao = new Person("zhao",19);
        linkedList.addLast(zhao);
        //返回集合第一个与最后一个元素
        System.out.println(linkedList.getFirst());
        System.out.println(linkedList.getLast());
        //删除集合中第一个或最后一个元素并返回
        System.out.println(linkedList.removeFirst());
        System.out.println(linkedList.removeLast());
    }
    
}

List特点

  • 使用List时,我们要关注List接口的规范。List接口允许我们添加重复的元素,即List内部的元素可以重复
  • 允许添加null

创建List

除了使用ArrayListLinkedList,我们还可以通过List接口提供的of()方法,根据给定元素快速创建List

List<Integer> list = List.of(1,2,3);

但是List.of()方法不接受null值,如果传入null,会抛出NullPointerException异常。

遍历List

  • 和数组类型相同,遍历一个List,可以用for循环根据索引配合get(int)方法遍历:
public class Main {
    public static void main(String[] args) {
        List<String> list = List.of("apple", "pear", "banana");
        for (int i=0; i<list.size(); i++) {
            String s = list.get(i);
            System.out.println(s);
        }
    }
}
  • 通过迭代器Iterator来遍历List。通过Iterator遍历List是最高效的方式。
public class Main {
    public static void main(String[] args) {
        List<String> list = List.of("apple", "pear", "banana");
      	//List实例调用iterator()创建Iterator对象
      	//boolean hasNext()判断是否有下一个元素
      	//E next()返回下一个元素
        for (Iterator<String> it = list.iterator(); it.hasNext(); ) {
            String s = it.next();
            System.out.println(s);
        }
    }
}
  • for-each循环遍历集合
public class Main {
    public static void main(String[] args) {
        List<String> list = List.of("apple", "pear", "banana");
        for (String s : list) {
            System.out.println(s);
        }
    }
}

List和Array转换

  • List变为Array有三种方法,第一种是调用toArray()方法直接返回一个Object[]数组:
public class Main {
    public static void main(String[] args) {
        List<String> list = List.of("apple", "pear", "banana");
      	//以正确顺序返回一个包含此列表中所有元素的数组
      	//此方法容易丢失类型信息,应用较少
        Object[] array = list.toArray();
        for (Object s : array) {
            System.out.println(s);
        }
    }
}
  • 第二种方式是给toArray(T[])传入一个类型相同的ArrayList内部自动把元素复制到传入的Array中:
public class Main {
    public static void main(String[] args) {
        List<Integer> list = List.of(12, 34, 56);
        Integer[] array = list.toArray(new Integer[3]);
        for (Integer n : array) {
            System.out.println(n);
        }
    }
}
  • 注意到这个toArray(T[])方法的泛型参数<T>并不是List接口定义的泛型参数<E>,所以,我们实际上可以传入其他类型的数组,例如我们传入Number类型的数组,返回的仍然是Number类型:
public class Main {
    public static void main(String[] args) {
        List<Integer> list = List.of(12, 34, 56);
        Number[] array = list.toArray(new Number[3]);
        for (Number n : array) {
            System.out.println(n);
        }
    }
}
  • 最常用的是传入恰好大小的数组
Integer[] array = list.toArray(new Integer[list.size()]);

Set

  • Set 集合类似于一个罐子,程序可以依次把多个对象“丢进”Set 集合,而 Set 集合通常不能记住元素的添加顺序。也就是说 Set 集合中的对象不按特定的方式排序,只是简单地把对象加入集合。Set 集合中不能包含重复的对象,并且最多只允许包含一个 null 元素。
  • Set 实现了 Collection 接口,它主要有两个常用的实现类:HashSet 类和 TreeSet类。

HashSet

  • HashSet 是 Set 接口的典型实现,大多数时候使用 Set 集合时就是使用这个实现类。HashSet 是按照 Hash 算法来存储集合中的元素。因此具有很好的存取和查找性能。
  • HashSet 特点:
    • 不能保证元素的排列顺序,顺序可能与添加顺序不同,顺序也有可能发生变化。
    • HashSet 不是同步的,如果多个线程同时访问或修改一个 HashSet,则必须通过代码来保证其同步。
    • 集合元素值可以是 null。
  • 当向 HashSet 集合中存入一个元素时,HashSet 会调用该对象的 hashCode() 方法来得到该对象的 hashCode 值,然后根据该 hashCode 值决定该对象在 HashSet 中的存储位置。**如果有两个元素通过 equals() 方法比较返回的结果为 true,但它们的 hashCode 不相等,**HashSet 将会把它们存储在不同的位置,依然可以添加成功。
  • 只有两个对象的 hashCode 值相等且通过 equals() 方法比较返回结果为 true,HashSet 集合才认为两个元素相等。
//创建HashSet对象
HashSet hs = new HashSet();    // 调用无参的构造函数创建HashSet对象
HashSet<String> hss = new HashSet<String>();    // 创建泛型的 HashSet 集合对象

TreeSet

  • **TreeSet 类同时实现了 Set 接口和 SortedSet 接口。SortedSet 接口是 Set 接口的子接口,可以实现对集合进行自然排序,**因此使用 TreeSet 类实现的 Set 接口默认情况下是自然排序的,这里的自然排序指的是升序排序。
  • **TreeSet 只能对实现了 Comparable 接口的类对象进行排序,**因为 Comparable 接口中有一个 compareTo(Object o) 方法用于比较两个对象的大小。例如 a.compareTo(b),如果 a 和 b 相等,则该方法返回 0;如果 a 大于 b,则该方法返回大于 0 的值;如果 a 小于 b,则该方法返回小于 0 的值。
比较方式
包装类(BigDecimal、Biglnteger、 Byte、Double、 Float、Integer、Long 及 Short)按数字大小比较
Character按字符的 Unicode 值的数字大小比较
String按字符串中字符的 Unicode 值的数字大小比较
  • TreeSet 类除 Collection 接口之外的方法
方法名称说明
E first()返回此集合中的第一个元素。其中,E 表示集合中元素的数据类型
E last()返回此集合中的最后一个元素
E poolFirst()获取并移除此集合中的第一个元素
E poolLast()获取并移除此集合中的最后一个元素
SortedSet subSet(E fromElement,E toElement)返回一个新的集合,新集合包含原集合中 fromElement 对象与 toElement 对象之间的所有对象。包含 fromElement 对象,不包含 toElement 对象
SortedSet headSet(E toElement)返回一个新的集合,新集合包含原集合中 toElement 对象之前的所有对象。 不包含 toElement 对象
SortedSet tailSet(E fromElement)返回一个新的集合,新集合包含原集合中 fromElement 对象之后的所有对 象。包含 fromElement 对象

Map

  • Map 是一种键-值对(key-value)集合,Map 集合中的每一个元素都包含一个键(key)对象和一个值(value)对象。用于保存具有映射关系的数据。
  • Map 接口主要有两个实现类:HashMap 类和 TreeMap 类。其中,HashMap 类按哈希算法来存取键对象,而 TreeMap 类可以对键对象进行排序。

Map中的常用方法

方法名称说明
void clear()删除该 Map 对象中的所有 key-value 对。
boolean containsKey(Object key)查询 Map 中是否包含指定的 key,如果包含则返回 true。
boolean containsValue(Object value)查询 Map 中是否包含一个或多个 value,如果包含则返回 true。
V get(Object key)返回 Map 集合中指定键对象所对应的值。V 表示值的数据类型
V put(K key, V value)向 Map 集合中添加键-值对,如果当前 Map 中已有一个与该 key 相等的 key-value 对,则新的 key-value 对会覆盖原来的 key-value 对。
void putAll(Map m)将指定 Map 中的 key-value 对复制到本 Map 中。
V remove(Object key)从 Map 集合中删除 key 对应的键-值对,返回 key 对应的 value,如果该 key 不存在,则返回 null
boolean remove(Object key, Object value)删除指定 key、value 所对应的 key-value 对。如果从该 Map 中成功地删除该 key-value 对,该方法返回 true,否则返回 false。
Set entrySet()返回 Map 集合中所有键-值对的 Set 集合,此 Set 集合中元素的数据类型为 Map.Entry
Set keySet()返回 Map 集合中所有键对象的 Set 集合
boolean isEmpty()查询该 Map 是否为空(即不包含任何 key-value 对),如果为空则返回 true。
int size()返回该 Map 里 key-value 对的个数
Collection values()返回该 Map 里所有 value 组成的 Collection

HashMap

HashMap是一个利用哈希表原理来存储元素的集合,并且允许空的key-value键值对。HashMap是非线程安全的,也就是说在多线程的环境下,可能会存在问题,而Hashtable是线程安全的容器。HashMap也支持fai-fast机制。HashMap的实例有两个参数影响其性能:**初始容量和加载因子。**可以使用Collections.synchronizedMap(new HashMap(..))来构造一个线程安全HashMap。


public class Map_a {

    public static void main(String[] args) {
        HashMap user = new HashMap();
        user.put("1","zhang");
        user.put("2","wang");
        user.put("3","liu");
        System.out.println(user);
        //删除键值为3的元素,返回value
        user.remove("3");
        System.out.println(user);
        //根据键返回返回指定对象的值
        System.out.println(user.get("1"));
        
    }

}

TreeMap

一个基于NavigableMap实现的红黑树。**这个map根据key自然排序存储,**或者通过Comparator进行定制排序。

  • TreeMap为containsKey,get,put和remove方法提供了(logn)的时间开销。
  • 注意这个实现不是线程安全的。如果多线程并发访问TreeMap,并且至少一个线程修改了map,必须进行外部加锁。这通常通过在自然封装集合的某个对象上进行同步来实现,或者使用SortedMap m Collections.synchronizedSortedMap(new TreeMap(...));
  • ·这个实现持有fail-fast机制。

常用类

Object类

Class Object 是类结构的根,是所有类的父类,所有类都默认继承Object类

类中方法

方法作用描述
protected Object clone()创建并返回此对象的副本
boolean equals(Object obj)指示其他对象是否等于此
protected void finalize()当垃圾收集确定不再有对该对象的引用时,垃圾收集器在对象上调用该对象
class<?> getClass()返回此Object的运行时类
int hashCode()返回对象的哈希码值
void notify()唤醒正在等待对象监视器单个线程
void notifyAll()唤醒正在等待对象监视器所有线程
String toString()返回对象的字符串表示形式。
void wait()导致当前线程等待,直到另一个线程调用该对象的 notify()方法或notifyAll()方法。
void wair(long timeout)导致当前线程等待,直到另一个线程调用该对象的 notify()方法或notifyAll()方法,或者指定时间已过
void wait(long timeout, int nanos)导致当前线程等待,直到另一个线程调用该对象的 notify()方法或notifyAll()方法,或者指定时间已过或某些其他线程中断当前线程
  • String toString() 返回对象的字符串表示形式
public class Person {

    private String name;

    private int age;

    public Person() {

    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + ''' +
                ", age=" + age +
                '}';
    }
}
  • protected Object clone()

返回一个对象的拷贝。

由于 Object 本身没有实现 Cloneable 接口,所以不重写 clone 方法并且进行调用的话会发生 CloneNotSupportedException 异常。

public class Person implements Cloneable{

    private String name;

    private int age;

    public Person() {

    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + ''' +
                ", age=" + age +
                '}';
    }

    public static void main(String[] args) throws CloneNotSupportedException {
        Person person = new Person("zcz", 20);
        //创建person的拷贝
        Person person1 = (Person) person.clone();
        System.out.println(person1.name);//zcz
        System.out.println(person1.age);//20
    }
}

String类

字符串广泛应用 在 Java 编程中,在 Java 中字符串属于对象,Java 提供了 String 类来创建和操作字符串。

String是一个引用类型,它本身也是一个class。但是,Java编译器对String有特殊处理,即可以直接用"..."来表示一个字符串:


创建字符串

  • String 创建的字符串存储在公共池中,而 new 创建的字符串对象在堆上
String str = "hello";

实际上字符串在内部是通过一个char[]数组表示的:

String str = new String(new char[]{'H', 'e', 'l', 'l', 'o', '!'})
  • java字符串的重要特点就是不可变,这种不可变性是通过内部的private final char[]字段,以及没有任何修改char[]的方法实现的。

字符串比较

  • 比较两个字符串是否相同时必须使用equals()而不是==
  • ==比较的是两个引用在内存中指向的是不是同一个对象,也就是内存空间中的存储位置是否一致
  • equals 常用的是比较对象里面的内容是否相等
public class Str {

    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "hello";
      	String s3 = new String("hello");

        System.out.println(s1 == s2);//true
        System.out.println(s1.equals(s2));//true
        System.out.println(s1 == s3);//false
        System.out.println(s1.equals(s3));//true
    }

}

字符串长度

  • 用于获取有关对象的信息的方法称为访问器方法。

    String 类的一个访问器方法是 length() 方法,它返回字符串对象包含的字符数。

public class StringDemo {
    public static void main(String args[]) {
        String site = "www";
        int len = site.length();
        System.out.println(len);//3
   }
}

连接字符串

String s1 = "hello";
System.out.println(s1.concat("world"));//helloworld
//+号也可用于连接字符串
System.out.println(s1 + "world");

操作子串

  • 搜索子串 索引号从0开始
// 是否包含子串:
"Hello".contains("ll"); // true

"Hello".indexOf("l"); // 2
"Hello".lastIndexOf("l"); // 3
"Hello".startsWith("He"); // true
"Hello".endsWith("lo"); // true
  • 提取子串
"Hello".substring(2); // "llo"
"Hello".substring(2, 4); "ll"
  • 去除首位空白字符
"  tHellorn ".trim(); // "Hello"

trim()并没有改变字符串的内容,而是返回了一个新字符串。

另一个strip()方法也可以移除字符串首尾空白字符。它和trim()不同的是,类似中文的空格字符u3000也会被移除:

"u3000Hellou3000".strip(); // "Hello"
" Hello ".stripLeading(); // "Hello "
" Hello ".stripTrailing(); // " Hello"
  • 判断空白字符串

String还提供了isEmpty()isBlank()来判断字符串是否为空和空白字符串

"".isEmpty(); // true,因为字符串长度为0
"  ".isEmpty(); // false,因为字符串长度不为0
"  n".isBlank(); // true,因为只包含空白字符
" Hello ".isBlank(); // false,因为包含非空白字符
  • 替换子串
String s = "hello";
s.replace('l', 'w'); // "hewwo",所有字符'l'被替换为'w'
s.replace("ll", "~~"); // "he~~o",所有子串"ll"被替换为"~~"

字符串方法

方法方法描述
char charAt(int index)返回指定索引处的 char 值。
int compareTo(Object o)把这个字符串和另一个对象比较。
int compareTo(String anotherString)按字典顺序比较两个字符串。
int compareToIgnoreCase(String str)按字典顺序比较两个字符串,不考虑大小写。
String concat(String str)将指定字符串连接到此字符串的结尾。
boolean contentEquals(StringBuffer sb)当且仅当字符串与指定的StringBuffer有相同顺序的字符时候返回真。
static String copyValueOf(char[] data)返回指定数组中表示该字符序列的 String。
static String copyValueOf(char[] data, int offset, int count)返回指定数组中表示该字符序列的 String。
boolean endsWith(String suffix)测试此字符串是否以指定的后缀结束。
boolean equals(Object anObject)将此字符串与指定的对象比较。
boolean equalsIgnoreCase(String anotherString)将此 String 与另一个 String 比较,不考虑大小写。
byte[] getBytes()使用平台的默认字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
byte[] getBytes(String charsetName)使用指定的字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)将字符从此字符串复制到目标字符数组。
int hashCode()返回此字符串的哈希码。
int indexOf(int ch)返回指定字符在此字符串中第一次出现处的索引。
int indexOf(int ch, int fromIndex)返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索。
int indexOf(String str)返回指定子字符串在此字符串中第一次出现处的索引。
int indexOf(String str, int fromIndex)返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。
int lastIndexOf(int ch)返回指定字符在此字符串中最后一次出现处的索引。
int lastIndexOf(int ch, int fromIndex)返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索。
int lastIndexOf(String str)返回指定子字符串在此字符串中最右边出现处的索引。
int lastIndexOf(String str, int fromIndex)返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索。
int length()返回此字符串的长度。
boolean matches(String regex)boolean matches(String regex) 告知此字符串是否匹配给定的正则表达式。
boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)测试两个字符串区域是否相等。
boolean regionMatches(int toffset, String other, int ooffset, int len)测试两个字符串区域是否相等。
String replace(char oldChar,char newChar)返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。
String replaceAll(String regex,String replacement)使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。
String replaceFirst(String regex,String replacement)使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。
String[]split(String regex)根据给定正则表达式的匹配拆分此字符串。
String split(String regex,int limit)根据匹配给定的正则表达式来拆分此字符串。
boolean startsWith(String prefix)测试此字符串是否以指定的前缀开始。
boolean startsWith(String prefix,int toffset)测试此字符串从指定索引开始的子字符串是否以指定前缀开始。
CharSequence subSequence(int beginlndex,int endlndex)返回一个新的字符序列,它是此序列的一个子序列。
String substring(int beginlndex)返回一个新的字符串,它是此字符串的一个子字符串。
String substring(int beginlndex,int endlndex)返回一个新字符串,它是此字符串的一个子字符串。
char[]toCharArray()将此字符串转换为一个新的字符数组。
String toLowerCase()使用默认语言环境的规则将此 String 中的所有字符都转换为小写。
String toLowerCase(Locale locale)使用给定 Locale 的规则将此 String 中的所有字符都转换为小写。
String toString()返回此对象本身(它已经是一个字符串!)。
String toUpperCase()使用默认语言环境的规则将此 String 中的所有字符都转换为大写。
String toUpperCase(Locale locale)使用给定 Locale 的规则将此 String 中的所有字符都转换为大写。
String trim()返回字符串的副本,忽略前导空白和尾部空白。
static String valueOf(primitive data type x)返回给定data type类型x参数的字符串表示形式。
contains(CharSequence chars)判断是否包含指定的字符系列。
isEmpty()判断字符串是否为空。

StringBuilder和StringBuffer类

  • 当对字符串进行修改的时候,需要使用 StringBuffer 和 StringBuilder 类。

  • 和 String 类不同的是,StringBuffer 和 StringBuilder 类的对象能够被多次的修改,并且不产生新的未使用对象。

  • 在使用 StringBuffer 类时,**每次都会对 StringBuffer 对象本身进行操作,而不是生成新的对象,**所以如果需要对字符串进行修改推荐使用 StringBuffer。

    StringBuilder 类在 Java 5 中被提出,它和 StringBuffer 之间的最大不同在于 StringBuilder 的方法不是线程安全的(不能同步访问)

    由于 StringBuilder 相较于 StringBuffer 有速度优势,所以多数情况下建议使用 StringBuilder 类。

public class Test{
    public static void main(String args[]){
				StringBuilder sb = new StringBuilder(10);
            //添加
            sb.append("oob..");
            System.out.println(sb);
            sb.append("!");
            System.out.println(sb);
            //插入
            sb.insert(6, "Java");
            System.out.println(sb);
            //删除
            sb.delete(6,9);
            System.out.println(sb); 
    }
}
/*结果:
	oob..
  oob..!
  oob..!Java
  oob..!a
*/

StringBuffer方法

序号方法描述
1public StringBuffer append(String s)
将指定的字符串追加到此字符序列。
2public StringBuffer reverse()
将此字符序列用其反转形式取代。
3public delete(int start, int end)
移除此序列的子字符串中的字符。
4public insert(int offset, int i)
int 参数的字符串表示形式插入此序列中。
5insert(int offset, String str)
str 参数的字符串插入此序列中。
6replace(int start, int end, String str)
使用给定 String 中的字符替换此序列的子字符串中的字符。
  • StringBuffer类其他方法:
序号方法描述
1int capacity()
返回当前容量。
2char charAt(int index)
返回此序列中指定索引处的 char 值。
3void ensureCapacity(int minimumCapacity)
确保容量至少等于指定的最小值。
4void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
将字符从此序列复制到目标字符数组 dst
5int indexOf(String str)
返回第一次出现的指定子字符串在该字符串中的索引。
6int indexOf(String str, int fromIndex)
从指定的索引处开始,返回第一次出现的指定子字符串在该字符串中的索引。
7int lastIndexOf(String str)
返回最右边出现的指定子字符串在此字符串中的索引。
8int lastIndexOf(String str, int fromIndex)
返回 String 对象中子字符串最后出现的位置。
9int length()
返回长度(字符数)。
10void setCharAt(int index, char ch)
将给定索引处的字符设置为 ch
11void setLength(int newLength)
设置字符序列的长度。
12CharSequence subSequence(int start, int end)
返回一个新的字符序列,该字符序列是此序列的子序列。
13String substring(int start)
返回一个新的 String,它包含此字符序列当前所包含的字符子序列。
14String substring(int start, int end)
返回一个新的 String,它包含此序列当前所包含的字符子序列。
15String toString()
返回此序列中数据的字符串表示形式。

System类

System系统类,主要用于获取系统的属性数据和其他操作,因其构造方法是私有的并且类中的成员方法都是静态的,所以在使用的时候不需要创建对象,可直接调用。

arraycopy()方法

将指定将指定源数组中的数组从指定位置复制到目标数组的指定位置。

static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);

src – 原数组。

srcPos – 在原数组中开始复制的位置。

dest – 目标数组。

destPos – 在目标数组中开始粘贴的位置。

length – 复制的长度。

public class demo4 {

    public static void main(String[] args) {
        int[] arr={1,2,3,4,5,6,7,8};
        int[] dest=new int[8];
        System.arraycopy(arr,4,dest,4,4);
        for (int x:dest) {
            System.out.print(x+" "); //0 0 0 0 5 6 7 8 
        }
    }

}

currentTimeMillis()方法

  • currentTimeMillis()方法返回当前时间(以毫秒为单位)。
static long currentTimeMillis();
public class demo4 {

    public static void main(String[] args) {
        //打印现在的时间
        System.out.println(System.currentTimeMillis());
        //该方法可用来计时
        long start=System.currentTimeMillis();
        for (int i = 0; i < ; i++) {
            System.out.println(i);
        }
        long end=System.currentTimeMillis();
        System.out.println("用时:"+(end-start));//用时:23873
    }

}

gc()方法

  • gc()方法用来运行垃圾回收器。(至于是否回收垃圾,有可能执行,有可能不执行,是否执行取决于JVM)
static void gc();
public class Person implements Cloneable{

    private String name;

    private int age;

    public Person() {

    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    protected void finalize() throws Throwable {
        System.out.println("回收了" + name + " " + age);
    }

    public static void main(String[] args) {
        new Person("ang",11);
        new Person("WANG",54);
        System.gc();
    }
}
//回收了WANG 54

exit(int status)方法

  • exit(int status)方法用于终止当前运行的Java虚拟机。如果参数是0,表示正常退出JVM;如果参数非0,表示异常退出JVM
static void exit(int status);
public class Test {
    public static void main(String[] args) {
        System.out.println("程序开始了");
        System.exit(0); //因为此处已经终止当前运行的Java虚拟机,故不会执行之后的代码
        System.out.println("程序结束了");
    }
}
//程序开始了

Date日期类

基本概念

  • java.util 包提供了 Date 类来封装当前的日期和时间。 Date 类提供两个构造函数来实例化 Date 对象。
Date();
Date(long millisec);
  • 时区与本地化

时区有好几种表示方式。

一种是以GMT或者UTC加时区偏移表示,例如:GMT+08:00或者UTC+08:00表示东八区。

另一种是缩写,例如,CST表示China Standard Time,也就是中国标准时间。但是CST也可以表示美国中部时间Central Standard Time USA,因此,缩写容易产生混淆,我们尽量不要使用缩写。

最后一种是以洲/城市表示,例如,Asia/Shanghai,表示上海所在地的时区。


在计算机中,通常使用Locale表示一个国家或地区的日期、时间、数字、货币等格式。Locale语言_国家的字母缩写构成,例如,zh_CN表示中文+中国,en_US表示英文+美国。语言使用小写,国家使用大写。

对于日期来说,不同的Locale,例如,中国和美国的表示方式如下:

  • zh_CN:2016-11-30
  • en_US:11/30/2016

Java标准库有两套处理日期和时间的API:

  • 一套定义在java.util这个包里面,主要包括DateCalendarTimeZone这几个类;
  • 一套新的API是在Java 8引入的,定义在java.time这个包里面,主要包括LocalDateTimeZonedDateTimeZoneId等。

Date

java.util.Date是用于表示一个日期和时间的对象,注意与java.sql.Date区分,后者用在数据库中。如果观察Date的源码,可以发现它实际上存储了一个long类型的以毫秒表示的时间戳:

public class Demo1 {

    public static void main(String[] args) {
        //获取当前时间
        Date date = new Date();
        System.out.println(date.getYear() + 1900); // 必须加上1900
        System.out.println(date.getMonth() + 1); // 0~11,必须加上1
        System.out.println(date.getDate()); // 1~31,不能加1
        // 转换为String:
        System.out.println(date.toString());
        // 转换为GMT时区:
        System.out.println(date.toGMTString());
        // 转换为本地时区:
        System.out.println(date.toLocaleString());
    }

}
/*
	结果:
	2022
  6
  29
  Wed Jun 29 03:10:28 CST 2022
  28 Jun 2022 19:10:28 GMT
  2022-6-29 3:10:28
*/

LocalDateTime

从Java 8开始,java.time包提供了新的日期和时间API,主要涉及的类型有:

  • 本地日期和时间:LocalDateTimeLocalDateLocalTime
  • 带时区的日期和时间:ZonedDateTime
  • 时刻:Instant
  • 时区:ZoneIdZoneOffset
  • 时间间隔:Duration

以及一套新的用于取代SimpleDateFormat的格式化类型DateTimeFormatter

public static void test01() {
        //默认时间时区
        LocalDateTime time = LocalDateTime.now();
        System.out.println(time);

        //手动指定时间
        LocalDateTime t1 = LocalDateTime.of(2022, 05, 30, 20, 34);
        System.out.println(t1);

        //指定时区获取LocalDateTime对象
        //ZoneId.of("")获取时区ID
        ZoneId zoneId = ZoneId.of("America/Los_Angeles");
        LocalDateTime time1 = LocalDateTime.now(zoneId);
        System.out.println(time1);
    }

ZonedDateTime

LocalDateTime总是表示本地日期和时间,要表示一个带时区的日期和时间,我们就需要ZonedDateTime

可以简单地把ZonedDateTime理解成LocalDateTimeZoneIdZoneIdjava.time引入的新的时区类,注意和旧的java.util.TimeZone区别。

要创建一个ZonedDateTime对象,有以下几种方法,一种是通过now()方法返回当前时间

 ZonedDateTime zbj = ZonedDateTime.now(); // 默认时区
 ZonedDateTime zny = ZonedDateTime.now(ZoneId.of("America/New_York")); // 用指定时区获取当前时间

DateTimeFormatter

使用旧的Date对象时,我们用SimpleDateFormat进行格式化显示。使用新的LocalDateTimeZonedDateTime时,我们要进行格式化显示,就要使用DateTimeFormatter

SimpleDateFormat不同的是,DateTimeFormatter不但是不变对象,它还是线程安全的。线程的概念我们会在后面涉及到。现在我们只需要记住:因为SimpleDateFormat不是线程安全的,使用的时候,只能在方法内部创建新的局部变量。而DateTimeFormatter可以只创建一个实例,到处引用。

创建DateTimeFormatter时,我们仍然通过传入格式化字符串实现:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

格式化字符串的使用方式与SimpleDateFormat完全一致。

另一种创建DateTimeFormatter的方法是,传入格式化字符串时,同时指定Locale

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E, yyyy-MMMM-dd HH:mm", Locale.US);
  • 使用printf格式化日期

printf方法可以格式化时间和日期,使用两个字母格式,它以 %t 开头并且以下面表格中的一个字母结尾。

转 换 符说 明示 例
c包括全部日期和时间信息星期六 十月 27 14:21:20 CST 2007
F"年-月-日"格式2007-10-27
D"月/日/年"格式10/27/07
r"HH:MM:SS PM"格式(12时制)02:25:51 下午
T"HH:MM:SS"格式(24时制)14:28:16
R"HH:MM"格式(24时制)14:28

日期时间字符串转换

  • 将时间毫秒数转为日期时间类型
//将时间毫秒数转为日期时间类型
    public static void test02() {
        //获取当前时间毫秒数第一种
        long time = System.currentTimeMillis();
        System.out.println(time);
        //第二种 Instant.now()
        Instant now = Instant.now();//获取当前瞬间
        long time1 = now.toEpochMilli();//返回毫秒数
        System.out.println(time1);

        //转为日期时间,创建Instant对象
        Instant ins = Instant.ofEpochMilli(time1);
        LocalDateTime time2 = LocalDateTime.ofInstant(ins,ZoneId.systemDefault());//默认时区
        System.out.println(time2);
    }
  • 将时区时间转为毫秒数
public static void test03(){
        LocalDateTime time = LocalDateTime.now();
  			//默认本地时区
        ZonedDateTime time1 = time.atZone(ZoneId.systemDefault());
        Instant instant = time1.toInstant();
        long timeMillis = instant.toEpochMilli();
        System.out.println(timeMillis);
    }
//1656443887995
  • 将LocalDateTime对象转为字符串
 public static void test04() {
        //获取时区
        ZoneId zone = ZoneId.of("America/Los_Angeles");
        //获取日期时间
        LocalDateTime time = LocalDateTime.now(zone);
        //创建DateTimeFormatter对象,指定模式字符串
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        String localDateTimeString = time.format(dateTimeFormatter);
        System.out.println(localDateTimeString);
    }
  • 将字符串转为LocalDateTime对象
 public static void test05() {
        //日期时间字符串格式1:1988-05-01 12:20:05
        String time = "1988-05-01 12:20:05";
        DateTimeFormatter datetime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.parse(time,datetime);
        System.out.println(localDateTime);

        //日期时间字符串格式2:1988-05-01T12:20:05.201Z
        String time1 = "1988-05-01T12:20:05.201Z";
        DateTimeFormatter datetime1 = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        LocalDateTime localDateTime1 = LocalDateTime.parse(time1, datetime1);
        System.out.println(localDateTime1);


        //日期字符串格式3:1988-05-01T12:20:05.201+08:00
        String time2 = "1988-05-01T12:20:05.201+08:00";
        //DateTimeFormatter datetime2 = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        LocalDateTime localDateTime2 = LocalDateTime.parse(time2, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
        System.out.println(localDateTime2);
    }
/*结果
1988-05-01T12:20:05
1988-05-01T12:20:05.201
1988-05-01T12:20:05.201
*/

最后

以上就是大气树叶为你收集整理的Java集合&常用类集合ListSetMap常用类的全部内容,希望文章能够帮你解决Java集合&常用类集合ListSetMap常用类所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(70)

评论列表共有 0 条评论

立即
投稿
返回
顶部