Java中的常用类常用方法

引言:

Java中常用类中的常用方法,如果能够记住,对刷题还是有一定的帮助的。

一、Object类

  • public final native Class<?> getClass();

native方法,用于返回当前运行时对象的Class对象,使用了final关键字修饰,故不允许子类重写。

  • public native int hashCode();

native方法,用于返回对象的哈希码,主要使用在哈希表中,比如JDK中的HashMap。

  • public boolean equals(Object obj)

用于比较2个对象的内存地址是否相等,String类对该方法进行了重写用户比较字符串的值是否相等。

  • protected native Object clone() throws CloneNotSupportedException;

naitive方法,用于创建并返回当前对象的一份拷贝。一般情况下,对于任何对象 x,表达式 x.clone() != x 为true;x.clone().getClass() == x.getClass() 为true。Object本身没有实现Cloneable接口,所以不重写clone方法并且进行调用的话会发生CloneNotSupportedException异常。

  • public String toString()

返回类的名字@实例的哈希码的16进制的字符串。建议Object所有的子类都重写这个方法。

  • public final native void notify();

native方法,并且不能重写。唤醒一个在此对象监视器上等待的线程(监视器相当于就是锁的概念)。如果有多个线程在等待只会任意唤醒一个。

  • public final native void notifyAll();

native方法,并且不能重写。跟notify一样,唯一的区别就是会唤醒在此对象监视器上等待的所有线程,而不是一个线程。

  • public final native void wait(long timeout) throws InterruptedException;

native方法,并且不能重写。暂停线程的执行,使线程进入阻塞状态。注意:sleep方法没有释放锁,而wait方法释放了锁。timeout 是等待时间,以毫秒为单位。

  • public final void wait(long timeout, int nanos) throws InterruptedException

多了nanos参数,这个参数表示额外时间(以毫微秒为单位,范围是 0-999999)。所以超时的时间还需要加上nanos 毫秒。

  • public final void wait() throws InterruptedException

该方法一直等待,没有超时时间这个概念

  • protected void finalize() throws Throwable

实例被垃圾回收器回收的时候触发的操作@Deprecated(since = “9”)

二、Objects工具类

  • public static <T> int compare(T a, T b, Comparator<? super T> c)
  • public static boolean **deepEquals(Object a, Objetc b):**可以深度比较两个数组是否相等
  • public static boolean equals(Object a, Objetc b)
  • public static int hash(Object… values)
  • public static int hashCode(Object o)
  • public static boolean isNull(Objetc obj)
  • public static boolean nonNull(Object obj)
  • public static <T> T requireNonNull(T obj)
  • public static <T> T **requireNonNull(T obj, String message):**抛出带指定消息异常
  • public static <T> T **requireNonNull(T obj, Supplier<String> messageSupplier):**抛出带指定消息异常
  • public static <T> T requireNonNullElse(T obj, T defaultObj)
  • public static <T> T requireNonNullElseGet(T obj, Supplier<? extends T> supplier)
  • public static String toString(Object o)
  • public static String toString(Object o, String nullDefault)
  • public static int **checkFromToIndex(int fromIndex, int toIndex, int length):**判断 [fromIndex, toIndex) 是否在 [0, length) 中
  • public static int **checkFromIndexSize(int fromIndex, int size, int length):**判断 [fromIndex, fromIndex + size) 是否在 [0, length) 中

三、String类

  1. int length():返回字符串的长度:return value.length

  1. char charAt(int index): 返回某索引处的字符return value[index]

  1. boolean isEmpty():判断是否是空字符串:return value.length == 0

  1. String toLowerCase():使用默认语言环境,将 String 中的所有字符转换为小写
  2. String toUpperCase():使用默认语言环境,将 String 中的所有字符转换为大写

转换后的值用新变量接受,调用者本身的值不变。(不可变性)


  1. String trim():返回字符串的副本,忽略前导空白和尾部空白,中间的空格不会忽略。

  1. boolean equals(Object obj):比较字符串的内容是否相同
  2. boolean equalsIgnoreCase(String anotherString):与equals方法类似,但忽略大小写进行比较

  1. String concat(String str):将指定字符串连接到此字符串的结尾。 等价于用“+”

  1. int compareTo(String anotherString):比较两个字符串的大小

  1. String substring(int beginIndex):返回一个新的字符串,它是此字符串的从beginIndex开始截取到最后的一个子字符串。
  2. String substring(int beginIndex, int endIndex) :返回一个新字符串,它是此字符串从beginIndex开始截取到endIndex(不包含)的一个子字符串。

  1. boolean endsWith(String suffix):测试此字符串是否以指定的后缀结束
  2. boolean startsWith(String prefix):测试此字符串是否以指定的前缀开始
  3. boolean startsWith(String prefix, int toffset):测试此字符串从指定索引开始的子字符串是否以指定前缀开始

  1. boolean contains(CharSequence s):当且仅当此字符串包含指定的 char 值序列时,返回 true

  1. int indexOf(String str):返回指定子字符串在此字符串中第一次出现处的索引
  2. int indexOf(String str, int fromIndex):返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引处开始向后寻找。但返回值还是相对于首字母开始,并不是从指定索引处开始
  3. int lastIndexOf(String str):返回指定子字符串在此字符串中最右边出现处的索引
  4. int lastIndexOf(String str, int fromIndex):返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索

**注:**indexOf和lastIndexOf方法如果未找到都是返回-1
什么情况下,indexOf(str)和lastIndexOf(str)返回值相同?①:存在唯一的一个str。②:不存在str

int indexOf(int ch)
int indexOf(int ch, int fromIndex)
int lastIndexOf(int ch)
int lastIndexOf(int ch, int fromIndex)


  1. String replace(char oldChar, char newChar):返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。
  2. String replace(CharSequence target, CharSequence replacement):使用指定的字面值替换序列替换此字符串所有匹配字面值目标序列的子字符串。
  3. String replaceAll(String regex, String replacement):使用给定replacement 替换此字符串所有匹配给定的正则表达式的子字符串。
  4. String replaceFirst(String regex, String replacement):使用给定的replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。

  1. boolean matches(String regex):告知此字符串是否匹配给定的正则表达式。

  1. String[] split(String regex):根据给定正则表达式的匹配拆分此字符串。
  2. String[] split(String regex, int limit):根据匹配给定的正则表达式来拆分此字符串,最多不超过limit个,如果超过了,剩下的全部都放到最后一个元素中。

  • 字符串 <–> 包装类
  1. 包装类.parseXxx(String str):包装类中的 public static xxx parseXxx(String s) 可以将由“数字”字符组成的字符串转换为基本数据类型。这类包装类包括Byte、Short、Integer、Long、Float、Double。
  2. public static String valueOf(xxx x):将相应的参数类型转换到字符串。valueOf(byte b)、valueOf(int i)、valueOf(long l)、valueOf(float f)、valueOf(double)、valueOf(boolean b)。

  • 字符串 --> 字符数组
  1. public char[] toCharArray():将字符串中的全部字符存放在一个字符数组中。
  2. public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin):将指定索引范围内的字符串存放到指定数组中

  • 字符数组 --> 字符串
  1. public static String valueOf(char[] data):将字符数组转换成字符串。
  2. public static String valueOf(char[] data, int offset, int count):用指定的字符数组的一部分,即从数组起始位置offset开始取count个字节构造一个字符串对象。
  3. String(char[] value):使用构造器
  4. String(chat[] value, int offset, int count):使用构造器,指定字符数组中的一部分来构造字符串。

  • 编码(String --> byte[])
  1. public byte[] getBytes():使用平台的默认字符集将此 String 编码为byte 序列,并将结果存储到一个新的 byte 数组中。
  2. public byte[] getBytes(Charset charset):使用指定的字符集将此 String 编码到 byte 序列,并将结果存储到新的 byte 数组。
  3. public byte[] getBytes(String charsetName):使用指定的字符集将此 String 编码到 byte 序列,并将结果存储到新的 byte 数组。

  • 解码(byte[] --> String)
  1. String(byte[] bytes):通过使用平台的默认字符集解码指定的 byte 数组,构造一个新的 String。
  2. String(byte[] bytes, Charset charset):指定字符集
  3. String(byte[] bytes, String charsetName):指定字符集
  4. String(byte[] bytes, int offset, int count):用指定的字节数组的一部分,即从数组起始位置offset开始取length个字节构造一个字符串对象。
  5. String(byte[] bytes, int offset, int count, Charset charset):指定字符集
  6. String(byte[] bytes, int offset, int count, String charsetName):指定字符集

四、StringBuffer(线程安全)、StringBuilder类

  1. 字符串拼接
  • StringBuffer append(boolean b)
  • StringBuffer append(char c)
  • StringBuffer append(charp[] str)
  • StringBuffer append(char[] str, int offset, int len)
  • StringBuffer append(double d)
  • StringBuffer append(float f)
  • StringBuffer append(int i)
  • StringBuffer append(long lng)
  • StringBuffer append(Object obj) //实际上是obj.toString()
  • StringBuffer append(String str)
  • StringBuffer append(StringBuffer sb)
  1. 删除
  • StringBuffer delete(int start, int end)
  • StringBuffer deleteCharAt(int index)
  1. 替换
  • StringBuffer replace(int start, int end, String str):把[start, end)位置替换为str
  • void setCharAt(int index, char ch):替换指定位置的字符
  1. 指定位置插入
  • StringBuffer insert(int offset, boolean b)
  • StringBuffer insert(int offset, char c)
  • StringBuffer insert(int offset, char[] str)
  • StringBuffer insert(int idnex, char[] str, int offset, int len)
  • StringBuffer insert(int offset, double d)
  • StringBuffer insert(int offset, float f)
  • StringBuffer insert(int offset, int i)
  • StringBuffer insert(int offset, long l)
  • StringBuffer insert(int offset, Object obj)
  • StringBuffer insert(int offset, String str)
  1. 查找
  • int indexOf(String str)
  • int indexOf(String str, int fromIndex)
  • int lastIndexOf(String str)
  • int lastIndexOf(String str, int fromIndex)
  1. 子串
  • String substring(int start)
  • String substring(int start, int end)
  1. 获取字符 char charAt(int index)
  2. 反转字符串 StringBuffer reverse()
  3. 总结:
  • **增:**append()
  • **删:**delete(int start, int end) / deleteCharAt(int index)
  • **改:**setCharAt(int index, char ch) / replace(int start, int end String str)
  • **查:**charAt(int index) / indexOf() / lastIndexOf()
  • **插:**insert()
  • **长度:**length()
  • **遍历:**for() + charAt() / toString()

五、Collection<E>接口中的通用方法

注意,Collection 接口是 List、Set 和 Queue 接口的父接口,该接口里定义的方法既可用于操作 Set 集合,也可用于操作 List 和 Queue 集合。JDK不提供此接口的任何直接实现,而是提供更具体的子接口(如:Set和List)实现。集合Collection中存储的如果是自定义类的对象,需要自定义类重写equals()方法,因为在调用equals()和contains()等方法时会用到。JDK 5.0增加了泛型,若未指定泛型 E 的具体类型,则默认为Object类型。

  1. 添加元素
  • **boolean add(E e):**添加单个元素
  • **boolean add(Collection<? extends E> c):**添加多个元素
  1. 获取有效元素个数:int size()
  2. 清空当前集合:void clear()
  3. 判断当前集合是否为空:boolean isEmpty()
  4. 判断是否包含某元素
  • **boolean contains(Object obj):**判断当前集合中是否包含形参元素。通过元素的equals()方法来判断是否为同一个对象。将当前集合中的元素依次作为obj.equals()方法的形参。
  • **boolean containsAll(Collection<?> c):**判断当前集合中是否包含形参集合中的所有元素。依次遍历形参集合c中的元素obj,然后将调用者集合中的元素依次作为obj.equals()方法的形参来进行判断。相当于形参集合c中的每个元素都要挨个与调用者集合中的每个元素进行判断(最坏的情况下)。
  1. 判断两个集合是否相等
  • **boolean equals(Objext o):**当前集合和形参集合的元素都相同时返回true。针对具体的有序集合List和无序集合Set,稍有不同。
  1. 删除元素
  • **boolean remove(Object o):**通过元素的equals()方法判断是否为要删除的那个方法。只会删除找到的第一个元素
  • boolean removeAll(Collection<?> c):相当于求差集
  • **default boolean removeIf(Predicate<? super E> filter):**删除该集合中满足给定条件的所有元素。(这里的形参类型是函数式接口类型,可以使用Lambda表达式)
  1. 取两个集合的交集
  • boolean remainAll(Collection<?> c):把交集的结果存入当前集合中,不影响形参集合c
  1. 转换成数组
  • **Object[] toArray():**转换成Object类型的数组
  • **<T> T[] toArray(T[] a):**转换成指定类型的数组
  1. 获取集合对象的哈希值:int hashCode()
  2. 遍历
  • **Iterator<E> iterator():**返回迭代器对象,用于遍历集合元素。
  • 增强For循环(底层采用Iterator来实现)
  • **void forEach(Consumer<? super T> action):**使用继承自Iterable接口的forEach方法。
  • 使用Stream新特新。Collection对象.stream().forEach(Consumer action)
  1. 其他默认方法(JDK 8在接口中可以定义默认方法)
  • default Stream<E> parallelStream()
  • default boolean removeIf(Predicate<? super E> filter)
  • default Spliterator<E> spliterator()
  • default Stream<E> stream()

六、List<E>接口中的通用方法

List除了从Collection集合中继承的方法外,还多了一些根据索引来操作集合元素的方法。因为我们知道List中存放的数据是有序的。

在Collection接口中就具有的方法:

  • boolean add(E e)
  • boolean addAll(Collection<? extends E> c)
  • int size()
  • int hashCode()
  • void clear()
  • boolean isEmpty()
  • boolean equals(Object o)
  • boolean contains(Object o)
  • boolean containsAll(Collection<?> c)
  • Iterator<E> iterator()
  • boolean remove(Object o)
  • boolean removeAll(Collection<?> c)
  • boolean retainAll(Collection<?> c)
  • Object[] toArray()
  • <T> T[] toArray(T[] a)
  • default boolean removeIf(Predicate<? super E> filter)
  • default Spliterator<E> spliterator()
  • default Stream<E> stream()
  • default Stream<E> parallelStream()

特有的方法:

  1. 在给定索引位置处添加元素
  • void add(int index, E element)
  • boolean addAll(int index, Collection<? extends E> c)
  1. 获取指定位置的元素:E get(int index)
  2. 查找元素
  • int indexOf(Objext o)
  • int lastIndexOf(Object o)
  1. 删除指定位置的元素并返回:E remove(int index)
  2. 替换(改)元素
  • E set(int index, E element)
  • **default void replaceAll(UnaryOperator<E> operator):**可能会用到Lambda表达式,UnaryOperator是函数式接口,对类型为E的对象进行一元运算,并返回E类型的结果。
  1. 获取子集:List<E> subList(int fromIndex, int toIndex)
  2. 定制排序:default void sort(Comparator<? super E> com)
  3. 遍历:
  • ListIterator<E> listIterator()
  • ListIterator<E> listIterator(int index)

总结:

增:add(Object o) / addAll(Collection c)
删:remove(Object o) / remove(int index) / removeAll(Collection c)
改:set(int index, Object obj) / repalceAll(UnaryOperator<E> operator)
取:get(int index)
查:indexOf(Object o) / lastIndexOf(Object o)
插:add(int index, Object o) / addAll(int index, Collection c)
长度:size()
遍历:①Iterator迭代器;②增强For循环;③普通循环(因为其具有索引);④forEach方法;⑤利用stream()方法转换成流后,再使用forEach()方法。

七、Set<E>接口中的通用方法

Set 接口是Collection接口的另一个子接口,没有提供额外的方法,其使用的都是Collection中声明过的方法。

  • boolean add(E e)
  • boolean addAll(Collection<? extends E> c)
  • int size()
  • int hashCode()
  • void clear()
  • boolean isEmpty()
  • boolean equals(Object o)
  • boolean contains(Object o)
  • boolean containsAll(Collection<?> c)
  • Iterator<E> iterator()
  • boolean remove(Object o)
  • boolean removeAll(Collection<?> c)
  • boolean retainAll(Collection<?> c)
  • Object[] toArray()
  • <T> T[] toArray(T[] a)
  • default boolean removeIf(Predicate<? super E> filter)
  • default Spliterator<E> spliterator()
  • default Stream<E> stream()
  • default Stream<E> parallelStream()

八、Map<K,V>接口中的常用方法

九、Collections工具类

Collections工具类提供了很多静态方法。不仅可以用来操作Collection,还能用来操作Map。
1.添加元素

  • public static <T> boolean addAll(Collection<? super T> c, T… elements)

2.排序

  • public static <T extends Comparable<? super T>> void sort(List<T> list):自然排序
  • public static <T> void sort(List<T> list, Comparator<? super T> c):定制排序
  • public static void reverse(List<?> list):逆序
  • public static <T> Comparator<T> reverseOrder():返回一个与自然排序逆序的比较器,要求泛型T需实现Comparabale接口。
  • public static <T> Comparator<T> reverseOrder(Comparator<T> cmp):返回一个与指定比较器逆序的比较器。
  • public static void shuffle(List<?> list):每次打乱的顺序都不一样
  • public static void shuffle(List<?> list, Random rnd):每次打乱的顺序一样
  • public static void swap(List<?> int i, int j):交换对应位置的元素

3.查找,统计

  • public static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key)
  • public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c)
  • public static int indexOfSubList(List<?> source, List<?> target)
  • public static int lastIndexOfSubList(List<?> source, List<?> target)
  • public static int frequency(Collection<?> c, Object o)
  • public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)
  • public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp)
  • public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll)
  • public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp)
  • public static disjoint(Collection<?> c1, Collection<?> c2):如果两个集合没有相同的集合,则返回 true

4.替换

  • public static <T> void fill(List<? super T> list, T obj)
  • public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal)

5.复制

  • public static <T> void copy(List<? super T> dest, List<? extends T> src)
  • public static <T> List<T> nCopies(int n, T o):将 o 复制 n 份,形成不可变 list 并返回

6.同步控制(返回线程安全的集合)

  • public static <T> Collection<T> synchronizedCollection(Collection<T> c)
  • public static <T> List<T> synchronizedList(List<T> list)
  • public static <T> Set<T> synchronizedSet(Set<T> s)
  • public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m)
  • public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s)
  • public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m)
  • public static <T> NavigableSet<T> synchronizedNavigableSet(NavigableSet<T> s)
  • public static <K,V> NavigableMap<K,V> synchronizedNavigableMap(NavigableMap<K,V> m)

7.返回一个空集合

  • public static <T> List<T> emptyList()
  • public static <T> Set<T> emptySet()
  • public static <K,V> Map<K,V> emptyMap()
  • public static <E> SortedSet<E> emptySortedSet()
  • public static <K,V> SortedMap<K,V> emptySortedMap()
  • public static <T> Enumeration<T> emptyEnumeration()
  • public static <T> Iterator<T> emptyIterator()
  • public static <T> ListIterator<T> emptyListIterator()
  • public static <E> NavigableSet<E> emptyNavigableSet()
  • public static <K,V> NavigableMap<K,V> emptyNavigableMap()

8.返回一个可进行元素类型检查(添加元素时)的集合,相当于将现有的集合封装成在添加元素时可以进行元素类型检查的集合。

  • public static <E> Collection<E> checkedCollection(Collection<E> c, Class<E> type)
  • public static <E> List<E> checkedList(List<E> list, Class<E> type)
  • public static <E> Set<E> checkedSet(Set<E> s, Class<E> type)
  • public static <K,V> Map<K,V> checkedMap(Map<K,V> m, Class<K> keyType, Class<V> valueType)
  • public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s, Class<E> type)
  • public static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K,V> m, Class<K> keyType, Class<V> valueType)
  • public static <E> Queue<E> checkedQueue(Queue<E> queue, Class<E> type)
  • public static <E> NavigableSet<E> checkedNavigableSet(NavigableSet<E> s, Class<E> type)
  • public static <K,V> NavigableMap<K,V> checkedNavigableMap(NavigableMap<K,V> m, Class<K> keyType, Class<V> valueType)

9.创建只读,不可改变的集合

  • public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c)
  • public static <T> List<T> unmodifiableList(List<? extends T> list)
  • public static <T> Set<T> unmodifiableSet(Set<? extends T> s)
  • public static <K, V> Map<K, V> unmodifiableMap(Map<? extends K, ? extends V> m)
  • public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s)
  • public static <K, V> SortedMap<K, V> unmodifiableSortedMap(SortedMap<K, ? extends V> m)
  • public static <T> NavigableSet<T> unmodifiableNavigableSet(NavigableSet<T> s)
  • public static <K, V> NavigableMap<K, V> unmodifiableNavigableMap(NavigableMap<K, ? extends V> m)

10.其他

  • public static <T> Enumeration<T> enumeration(Collection<T> c)
  • public static <E> Set<E> newSetFromMap(Map<E,Boolean> map):提供一个和 Map 实现相对应的Set实现

未完待续…

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值