Java.util库 + Java.lang库基础知识

Arrays类

java.util.Arrays 类能方便地操作数组,它提供的所有方法都是静态的。提供功能如下:

  1. asList()方法。将数组转换为一个定长的list。这是一个连接了array 和 collection的API。相对应的还有Collection.toArray()。
public static <T> List<T> asList(T... a)
//eg
List<String> s = Arrays.asList("Larry", "Moe", "Curly");
List<Integer> value  = Arrays.asList(nums);
  1. binarySearch() 方法。对排序的数组进行二分查找。用二分查找算法在给定数组中搜索给定值的对象(Byte,Int,double等)。数组在调用前必须排序好的。如果查找值包含在数组中,则返回搜索键的索引;否则返回 (-(应该插入点) - 1)。

fromIndex为开始搜索的第一个下标,包括它;toIndex为结束搜索的下标,不包括。

public static int binarySearch(Object[] a, Object key)
//eg
int index = Arrays.binarySearch(nums, n);

public static int binarySearch(Object[] a, int fromIndex, int toIndex, Object key)

  1. copyOf() 方法。复制数组为一个新的长度为newLength的数组。可能会删掉超出范围的元素,如果不足则补充0或者null。
public static int[] copyOf(int[] original,
           int newLength)
//eg
int[] index = Arrays.copyOf(nums, n);

//geeks for geek
// initializing an array original 
        int[] org = new int[] {1, 2 ,3}; 
  
        System.out.println("Original Array"); 
        for (int i = 0; i < org.length; i++) 
            System.out.print(org[i] + " "); 
  
        // copying array org to copy 
        int[] copy = Arrays.copyOf(org, 5); 
  
        // Changing some elements of copy 
        copy[3] = 11; 
        copy[4] = 55; 
  
        System.out.println("\nNew array copy after modifications:"); 
        for (int i = 0; i < copy.length; i++) 
            System.out.print(copy[i] + " "); 
  1. copyOfRange() 方法。复制指定范围内的数组元素为一个新的数组,新数组的内容为from 到 to的元素。
    from为开始搜索的第一个下标,包括它;to为结束搜索的下标,不包括。
public static int[] copyOfRange(int[] original,
           int from, int to)
//eg
int[] index = Arrays.copyOf(nums, n);
  1. equals() 方法。如果两个同样类型数组彼此相等,则返回 true。如果两个数组包含相同数量的元素,并且两个数组中的所有相应元素对都是相等的,则认为这两个数组是相等的。换句话说,如果两个数组以相同顺序包含相同的元素,则两个数组是相等的。同样的方法适用于所有的其他基本数据类型(Byte,short,Int等)。
public static boolean equals(long[] a, long[] a2)

//eg
if (Arrays.equals(nums1, nums2){
	//do something
}
  1. fill() 方法。将指定的值分配给指定类型数组指定范围中的每个元素。同样的方法适用于所有的其他基本数据类型(Byte,short,Int等)。
    也可以对指定范围的元素进行赋值。
    fromIndex为开始赋值的第一个下标,包括它;toIndex为结束赋值的下标,不包括。
public static void fill(int[] a, int val)
//eg
Arrays.fill(nums, 1);

public static void fill(int[] a, int fromIndex, int toIndex, int val)
//eg
Arrays.fill(nums, 1, 3, 233);
  1. hashCode() 方法。根据数组内容,返回它的hash code。
public static int hashCode(Object[] a)

//eg
int hash = Arrays.hashCode(nums);
  1. sort() 方法。对指定对象数组根据其元素的自然顺序进行升序排列。同样的方法适用于所有的其他基本数据类型(Byte,short,Int等)。

可以通过指定fromIndex,toIntex指定排序的范围,同样的toIndex是不包括的。

也可以自己定义Comparator来实现降序排序或其他特殊的排序方法(比如数组中存放TreeNode)。所有数组中的元素都要根据Comparator的定义进行排序。

public static void sort(Object[] a)
//eg
Arrays.sort(nums);

public static void sort(Object[] a, int fromIndex, int toIndex)
//eg
Arrays.sort(nums, 2, 233);

public static void sort(Object[] a, Comparator<? super T> c)
//eg
int[] nums = new int[]{5, 4, 2, 1, 3};
Arrays.sort(nums, new Comparator<Integer>() {
    public int compare(Integer o1, Integer o2){
        return o2.compareTo(o1);
    }
});
  1. toString() 方法。将基本数组类型的数组转换为包含了数组内容的String形式。
public static String toString(Object[] a)

//eg
String s = Arrays.toString(nums);

Character类

来自于java.lang.Character。Character 类用于对单个字符进行操作。Character 类在对象中包装一个基本类型 char 的值。

char ch = 'a';
 
// Unicode 字符表示形式
char uniChar = '\u039A'; 
 
// 字符数组
char[] charArray ={ 'a', 'b', 'c', 'd', 'e' };

实际开发过程中,我们经常会遇到需要使用对象,而不是内置数据类型的情况。为了解决这个问题,Java语言为内置数据类型char提供了包装类Character类。

实际上Character类提供了大量的静态变量表示Unicode下的特殊字符以及很多方法,不再赘述。

Character类提供了一系列方法来操纵字符。你可以使用Character的构造方法创建一个Character类对象,实现对char类型参数的操作。

  1. isLetter()方法。判断一个字符是不是字母。
public static boolean isLetter(char ch)
//eg
if (Character.isLetter('a')){
	//do something
}
  1. isDigit()方法。判断一个字符是不是数字。
public static boolean isDigit(char ch)
//eg
if (Character.isDigit('2')){
	//do something
}
  1. isWhitespace()方法。判断一个字符是不是空白字符。
public static boolean isWhitespace(char ch)
//eg
if (Character.isWhitespace(' ')){
	//do something
}
  1. isUpperCase()方法。判断一个字符是不是大写字母。
public static boolean isUpperCase(char ch)
//eg
if (Character.isUpperCase('G')){
	//do something
}
  1. isLowerCase()方法。有大写就有小写
public static boolean isLowerCase(char ch)
//eg
if (Character.isLowerCase('b')){
	//do something
}
  1. toUpperCase()方法。将字符转为大写格式。
public static char toUpperCase(char ch)
//eg
char upper = Character.toUpperCase('a');
  1. toLowerCase()方法。将字符转为小写格式。
public static char toLowerCase(char ch)
//eg
char lower = Character.toLowerCase('A');
  1. toString()方法。返回字符的字符串形式,字符串的长度仅为1。也可直接对char使用。
public static String toString(char ch)
public String toString(char ch)
//eg
String s = Character.toString('2');
char ch = 'a';
s = ch.toString()

一些其他有用的方法:

  1. compare()方法。数值上比较两个char。如果x == y,返回0; x < y,返回负数; x > y,返回正数。返回值等同于使用compareTo()。
public static int compare(char x, char y)
//eg
int diff = Character.compare('2', 'd');
//It is indentical to
int diff = Character.valueOf(x).compareTo(Character.valueOf(y));
  1. compareTo()方法。依然是比较,若比较元素为x,被比较元素为y。如果x == y,返回0; x < y,返回负数; x > y,返回正数。与compare()类似。
public int compareTo(Character anotherCharacter)
//eg
char x = 'e', y = 'b';
int diff = x.compareTo(y);
  1. valueOf()方法。返回一个Character对象代表了传入的char。
public static Character valueOf(char c)
//eg
Character c = Character.valueOf(ch);

Collection接口

源自于java.util。Java 集合框架主要包括两种类型的容器,一种是集合(Collection),存储一个元素集合,另一种是图(Map),存储键/值对映射。Collection 接口又有 3 种子类型,List、Set 和 Queue,再下面是一些抽象类,最后是具体实现类,常用的有 ArrayList、LinkedList、Vector、HashSet、LinkedHashSet、HashMap、LinkedHashMap 等等。尽管 Map 不是集合,但是它们完全整合在集合中。
集合类详解

  1. add()方法。增加一个元素。(optional)
public boolean add(E e)
  1. addAll()方法。将一个Collection中的元素加入另一个集合中。(optional)
public boolean addAll(Collection<? extends E> c )
  1. clear()方法。删除Collection中的所有元素。(optional)
public void clear(E e)
  1. contains()方法。判断collection 是否包含某个元素。
public boolean contains(Object o)
  1. containsAll()方法。判断collection 是否包含某collection 中所有元素。
public boolean containsAll(Collection<? extends E> c )
  1. equals()方法。判断集合是否与这个对象相同。
public boolean equals(Object o)
  1. hashCode()方法。返回collection的hash code
public int hashCode()
  1. isEmpty()方法。返回collection是否为空。
public boolean isEmpty()
  1. remove()方法。删除collection中的一个元素。(optional)
public boolean remove(Object o)
  1. removeAll()方法。删除collection中的所有传入的collection的元素。(optional)
public int removeAll(Collection<? extends E> c )
  1. size()方法。返回collection大小
public int size()
  1. toArray()方法。将collection转为array
public Object[] toArray()

Comparator

源自于java.util。Comparator 是比较器接口。我们若需要控制某个类的次序,而该类本身不支持排序(即没有实现Comparable接口);那么,我们可以建立一个“该类的比较器”来进行排序。这个“比较器”只需要实现Comparator接口即可。

也就是说,我们可以通过“实现Comparator类来新建一个比较器”,然后通过该比较器对类进行排序。

Comparator 借口包括两个函数:

package java.util;

public interface Comparator<T> {

    int compare(T o1, T o2);

    boolean equals(Object obj);
}
  1. 若一个类要实现Comparator接口:它一定要实现compare(T o1, T o2) 函数,但可以不实现 equals(Object obj)函数。
    为什么可以不实现 equals(Object obj) 函数呢? 因为任何类,默认都是已经实现了equals(Object obj)的。 Java中的一切类都是继承于java.lang.Object,在Object.java中实现了equals(Object obj)函数;所以,其它所有的类也相当于都实现了该函数。

  2. int compare(T o1, T o2) 是“比较o1和o2的大小”。返回“负数”,意味着“o1比o2小”;返回“零”,意味着“o1等于o2”;返回“正数”,意味着“o1大于o2”。
    排序永远是为了把小的排在前面,例如当返回负数的时候,表明第一个数应该排在第二个数的前面。

关于如何记忆返回值。我们认为o1是处在前面的元素o2是后面的元素。返回“正数”可以理解为true,我们想要调整顺序,将o2提前;返回“负数”理解为false,不想调整顺序。return o2 - o1;就可以实现降序排序了。


Integer 类

来自java.lang库,是基本数据类型int的包装类。int与integer的区别从大的方面来说就是基本数据类型与其包装类的区别。int 是面向过程留下的痕迹,不过是对java的有益补充。Integer 是一个类,是int的扩展,定义了很多的转换方法,还提供了处理 int 类型时非常有用的其他一些常量和方法

类似的还有:float Float;double Double;string String等。

  1. int 是基本类型,直接存数值,而Integer是对象,用一个引用指向这个对象。

  2. Java 中的数据类型分为基本数据类型和复杂数据类型int 是前者而Integer 是后者(也就是一个类);因此在类进行初始化时int类的变量初始为0.而Integer的变量则初始化为null.

初始化时:

int i = 1;
Integer i = new Integer(1);  

Integer的静态变量有:
3. MAX_VALUE。是一个代表了 2 31 − 1 2^{31} - 1 2311的常量

public static final int MAX_VALUE
//eg
int res = Integer.MAX_VALUE;
  1. MIN_VALUE。是一个代表了 − 2 31 -2^{31} 231 的常量
public static final int MIN_VALUE
//eg
int res = Integer.MIN_VALUE;

Integer提供的方法有:
5. Constructor()方法。创建一个新的Intger对象

public Integer(int);
//eg
Integer in = new Integer(1);
  1. bigCount()方法。返回二进制表示的int中1位的个数,又被称为population count
public static int bitCount(int i)
//eg
int n = Integer.bitCount(i);
  1. compare()方法。比较两个int的大小,如果x == y,返回0; x < y,返回负数; x > y,返回正数。返回值等同于使用compareTo()。
public static int compare(int x, int y)
//eg
int n = Integer.compare(x, y);
//is identival to
Integer.valueOf(x).compareTo(Integer.valueOf(y))
  1. compareTo()方法。比较int与被比较数的大小。
public int compareTo(Integer anotherInteger)
//eg
Integer.valueOf(x).compareTo(Integer.valueOf(y));
  1. doubleValue()方法。将int转位double
public double doubleValue()
//eg
double d = Integer.doubleValue(x);
  1. floatValue()方法。将int转位float
public float floatValue()
//eg
double d = Integer.floatValue(x);
  1. LongValue()方法。将int转位Long

  2. parseInt()方法,将string转为int。如果不行抛出NumberFormatException。可以使用radix规定由那种进制转换。

public static int parseInt(String s)
public static int parseInt(String s, int radix)
//eg
int num = Integer.parseInt("123");
num = Integer.parseInt("1100110", 2);
  1. reverse()方法,将int按照二进制位反转。
public static int reverse(int i)
//eg
int num = Integer.reverse(2333);
  1. toString() 方法,将int转为String。注意这是在Integer上进行的操作,int不行。
public String toString()
public static String toString(int i)
public static String toString(int i, int radix)
public static String toBinaryString(int i)//二进制
public static String toOctalString(int i)//八进制
public static String toHexString(int i)//十六进制
//eg
Integer n = Integer.valueOf(2);
String s = n.toString();
s = Integer.toString(2);
s = Integer.toString(2, 8);
s = Integer.toBinaryString(2);
s = Integer.toOctalString(2);
s = Integer.toHexStrin(2);
  1. valueOf()方法,返回一个Integer对象。可以用radix表示输入String的进制格式。
public static Integer valueOf(int i)
public static Integer valueOf(String s)
public static Integer valueOf(String s, int radix)
//eg
Integer n = Integer.valueOf(2);
//更多用于这样格式
int a = Integer.valueOf(123).intValue();

HashMap 类

源自于java.util。
Java中的数据存储方式有两种结构,一种是数组,另一种就是链表,前者的特点是连续空间,寻址迅速,但是在增删元素的时候会有较大幅度的移动,所以数组的特点是查询速度快,增删较慢。
而链表由于空间不连续,寻址困难,增删元素只需修改指针,所以链表的特点是查询速度慢、增删快。

而Map通过映射,综合了两种数据结构的优点

HashMap和HashTable的不同

  1. HashMap几乎可以等价于Hashtable,除了HashMap是非synchronized的,并可以接受null(HashMap可以接受为null的键值(key)和值(value),而Hashtable则不行)。
  2. HashMap是非synchronized,而Hashtable是synchronized,这意味着Hashtable是线程安全的,多个线程可以共享一个Hashtable;而如果没有正确的同步的话,多个线程是不能共享HashMap的。Java 5提供了ConcurrentHashMap,它是HashTable的替代,比HashTable的扩展性更好。
  3. 另一个区别是HashMap的迭代器(Iterator)是fail-fast迭代器,而Hashtable的enumerator迭代器不是fail-fast的。所以当有其它线程改变了HashMap的结构(增加或者移除元素),将会抛出ConcurrentModificationException,但迭代器本身的remove()方法移除元素则不会抛出ConcurrentModificationException异常。但这并不是一个一定发生的行为,要看JVM。这条同样也是Enumeration和Iterator的区别。
  4. 由于Hashtable是线程安全的也是synchronized,所以在单线程环境下它比HashMap要慢。如果你不需要同步,只需要单一线程,那么使用HashMap性能要好过Hashtable。
  5. HashMap不能保证随着时间的推移Map中的元素次序是不变的。

方法:

  1. Constructor()方法。创建一个新的HashMap

//eg
HashMap<Integer, Integer> map = new HashMap<>();
  1. clear()方法。清空HashMap。
public void clear()
//eg
Map<Integer, Integer> map = new HashMap<>();
map.put(1,2);
map.clear();
  1. containsKey()方法。判断Map是否含有特定的key
public boolean containsKey(Object key)

//eg
Map<Integer, Integer> map = new HashMap<>();
map.put(1,2);
boolean exist = map.containsKey(1);
  1. containsValue()方法。判断Map是否含有特定的value
public boolean containsValue(Object value)
//eg
Map<Integer, Integer> map = new HashMap<>();
map.put(1,2);
boolean exist = map.containsValue(2);
  1. entrySet()方法。返回一个map的entry set,多用于遍历map。可以使用getKey(), getValue(), setValue()等方法。foreach遍历时使用Map.Entry<Integer, String> for example.
public Set<Map.Entry<K,V>> entrySet()
//eg
// Creating an empty HashMap 
        HashMap<Integer, String> hash_map = new HashMap<Integer, String>(); 
  
        // Mapping string values to int keys 
        hash_map.put(10, "Geeks"); 
        hash_map.put(15, "4"); 
        hash_map.put(20, "Geeks"); 
        hash_map.put(25, "Welcomes"); 
        hash_map.put(30, "You"); 
  
        // Displaying the HashMap 
        System.out.println("Initial Mappings are: " + hash_map); 
  
        // Using entrySet() to get the set view 
        System.out.println("The set is: " + hash_map.entrySet()); 
  1. isEmpty()方法。判断Map是否为空。
public boolean isEmpty()
//eg
Map<Integer, Integer> map = new HashMap<>();
map.put(1,2);
boolean empty = map.isEmpty();
  1. keySet()方法。得到一个map的key set。这个key set是基于map产生的,对他的操作将会反应在map上,反之亦然。
// Creating an empty HashMap 
        HashMap<String, Integer> hash_map = new HashMap<String, Integer>(); 
  
        // Mapping int values to string keys 
        hash_map.put("Geeks", 10); 
        hash_map.put("4", 15); 
        hash_map.put("Geeks", 20); 
        hash_map.put("Welcomes", 25); 
        hash_map.put("You", 30); 
  
        // Displaying the HashMap 
        System.out.println("Initial Mappings are: " + hash_map); 
  
        // Using keySet() to get the set view of keys 
        System.out.println("The set is: " + hash_map.keySet()); 
  1. get()方法。根据key得到value。
public V get(Object key)
//eg
Map<Integer, Integer> map = new HashMap<>();
map.put(1,2);
int a = map.get(1);
  1. getOrDefault()方法。根据key得到value,如果不存在返回default值。
public V getOrDefault(Object key, V value)
//eg
Map<Integer, Integer> map = new HashMap<>();
map.put(1,2);
int a = map.getOrDefault(3, 0);
  1. put()方法。将一组键值对放入map中。返回值为之前存放为这个key的value值,如果没有返回null。
public V put(K key, V value)
//eg
Map<Integer, Integer> map = new HashMap<>();
map.put(1,2);
  1. putAll()方法。将一个map中的映射转移过来。
void putAll(Map<? extends K,? extends V> m)
//eg
Map<Integer, Integer> map = new HashMap<>();
map.put(1,2);
Map<Integer, Integer> map2 = new HashMap<>();
map2.putAll(map);
  1. remove()方法。将一组map中的键值对删除。如果存在就返回value,不存在返回null
public V remove(Object key)
//eg
Map<Integer, Integer> map = new HashMap<>();
map.put(1,2);
map.remove(1)
  1. size()方法。map中键值对的数量。如果超过整数上限,只返回Integer.MAX_VALUE
public int size()
//eg
Map<Integer, Integer> map = new HashMap<>();
map.put(1,2);
int size = map.size();
  1. values()方法。返回map中value的一个collection
public Collection<V> values()
//eg
// Creating an empty HashMap 
        HashMap<Integer, String> hash_map = new HashMap<Integer, String>(); 
  
        // Mapping string values to int keys 
        hash_map.put(10, "Geeks"); 
        hash_map.put(15, "4"); 
        hash_map.put(20, "Geeks"); 
        hash_map.put(25, "Welcomes"); 
        hash_map.put(30, "You"); 
  
        // Displaying the HashMap 
        System.out.println("Initial Mappings are: " + hash_map); 
  
        // Using values() to get the set view of values 
        System.out.println("The collection is: " + hash_map.values()); 

List 类

来自java.util库,相比于数组(Array)来说,集合类的长度可变,更加适合于现代开发需求;

Java集合就像一个容器,可以存储任何类型的数据,也可以结合泛型来存储具体的类型对象。在程序运行时,Java集合可以动态的进行扩展,随着元素的增加而扩大。在Java中,集合类通常存在于java.util包中。

Java集合主要由2大体系构成,分别是Collection体系和Map体系,其中Collection和Map分别是2大体系中的顶层接口。

Collection主要有三个子接口,分别为List(列表)、Set(集)、Queue(队列)。其中,List、Queue中的元素有序可重复,而Set中的元素无序不可重复;

List中主要有ArrayList、LinkedList两个实现类;Set中则是有HashSet实现类;而Queue是在JDK1.5后才出现的新集合,主要以数组和链表两种形式存在。

Map同属于java.util包中,是集合的一部分,但与Collection是相互独立的,没有任何关系。Map中都是以key-value的形式存在,其中key必须唯一,主要有HashMap、HashTable、TreeMap三个实现类。
List简介

在Collection中,List集合是有序的,Developer可对其中每个元素的插入位置进行精确地控制,可以通过索引来访问元素,遍历元素。

在List集合中,我们常用到ArrayList和LinkedList这两个类。

其中,ArrayList底层通过数组实现,随着元素的增加而动态扩容。而LinkedList底层通过链表来实现,随着元素的增加不断向链表的后端增加节点。

ArrayList
ArrayList是Java集合框架中使用最多的一个类,是一个数组队列,线程不安全集合。

它继承于AbstractList,实现了List, RandomAccess, Cloneable, Serializable接口。
(1)ArrayList实现List,得到了List集合框架基础功能;
(2)ArrayList实现RandomAccess,获得了快速随机访问存储元素的功能,RandomAccess是一个标记接口,没有任何方法;
(3)ArrayList实现Cloneable,得到了clone()方法,可以实现克隆功能;
(4)ArrayList实现Serializable,表示可以被序列化,通过序列化去传输,典型的应用就是hessian协议。

它具有如下特点:

  • 容量不固定,随着容量的增加而动态扩容(阈值基本不会达到)
  • 有序集合(插入的顺序==输出的顺序)
  • 插入的元素可以为null
  • 增删改查效率更高(相对于LinkedList来说)
  • 线程不安全

LinkedList
LinkedList是一个双向链表,每一个节点都拥有指向前后节点的引用。相比于ArrayList来说,LinkedList的随机访问效率更低。

它继承AbstractSequentialList,实现了List, Deque, Cloneable, Serializable接口。
(1)LinkedList实现List,得到了List集合框架基础功能;
(2)LinkedList实现Deque,Deque 是一个双向队列,也就是既可以先入先出,又可以先入后出,说简单些就是既可以在头部添加元素,也可以在尾部添加元素;
(3)LinkedList实现Cloneable,得到了clone()方法,可以实现克隆功能;
(4)LinkedList实现Serializable,表示可以被序列化,通过序列化去传输,典型的应用就是hessian协议。

构造方法

List<String> list = new ArrayList<String>();
List<Integer> l = new LinkedList<>();

我们可以发现,list实现了collection的大部分功能。

  1. add()方法。增加一个元素。
public boolean add(E e)
//add element to corresponding index
public boolean add(int index, E element)

//eg
List<Integer> list = new ArrayList<Integer>();
list.add(123);
list.add(231);
list.add(1, 321);
  1. addAll()方法。将一个Collection中的元素加入另一个list中。
public boolean addAll(Collection<? extends E> c )
//Inserts all of the elements in the specified collection into this list at the specified position (optional operation).
public boolean addAll(int index, Collection<? extends E> c )

//eg
List<Integer> list = new ArrayList<Integer>();
list.add(123);
list.add(231);
list.add(1, 321);

List<Integer> l2 = new ArrayList<Integer>();
l2.addAll(list);

  1. clear()方法。删除list中的所有元素。
public void clear(E e)

//eg
list.clear();
  1. contains()方法。判断list 是否包含某个元素。
//Returns true if this list contains the specified element.
public boolean contains(Object o)

//eg
list.contains(123)
  1. containsAll()方法。判断collection 是否包含某collection 中所有元素。
//Returns true if this list contains all of the elements of the specified collection.
public boolean containsAll(Collection<? extends E> c )

//eg
list.containsAll(list2);
  1. equals()方法。判断list是否与这个对象相同。
public boolean equals(Object o)

//eg
list.equals(list2);
  1. hashCode()方法。返回collection的hash code
//Returns the hash code value for this list.
public int hashCode()
  1. indexOf()方法,找到这个object在list中第一次出现的位置,如果没有就返回-1;
//Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
public int indexOf(Object o)

//eg
int index = list.indexOf(123);

9.isEmpty()方法。返回list是否为空。

public boolean isEmpty()

//eg
boolean empty = list.isEmpty();
  1. iterator()方法,返回一个可以遍历list的Iterator
//Returns an iterator over the elements in this list in proper sequence.
public Iterator<E> iterator()

//eg
Iterator<Integer> it = list.iterator();
  1. lastIndexOf()方法,与indexOf()相反,返回的是最后一次出现的index。
public int lastIndexOf(Object o)

//eg
int index = list.lastIndexOf(123);
  1. remove()方法。删除list中的一个元素。一个是给index删除,可以返回被删除的元素;另一个是删除是给一个特定元素。返回删除的元素的index。
//Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the list.
public E remove(int index)
//Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
public int remove(Object o)

//eg
list.remove(0);
list.remove("ddd");
  1. removeAll()方法。删除list中的所有传入的collection的元素。(optional)
public int removeAll(Collection<? extends E> c )

//eg
list.removeAll(list2);
  1. set()方法。将list指定位置的元素进行替换
public E set(int index, E element)

//eg
list.set(1, "ddd");
  1. size()方法。返回list大小
public int size()

//eg
int size = list.size();
  1. toArray()方法。将list转为array. 第一种方法返回的是Object数组,需要做强制类型转换;第二种先new 一个新数组,会比较优雅。
    ArrayList to Array Conversion in Java : toArray() Methods
//Returns an array containing all of the elements in this list in proper sequence (from first to last element).
public Object[] toArray()
public <T> T[] toArray(T[] a)

//eg1
Object[] objects = list.toArray(); 

//eg2
Integer[] arr = new Integer[list.size()];
arr = list.toArray(arr);

  1. toArray()方法。将collection转为array
public Object[] toArray()

PriorityQueue 类

源自于java.util。
PriorityQueue类在Java1.5中引入并作为 Java Collections Framework 的一部分。PriorityQueue是基于最小堆的一个无界队列,这个优先队列中的元素可以**默认自然排序(升序)**或者通过提供的Comparator(比较器)在队列实例化的时排序。

优先队列不允许空值,而且不支持non-comparable(不可比较)的对象,比如用户自定义的类。优先队列要求使用Java Comparable和Comparator接口给对象排序,并且在排序时会按照优先级处理其中的元素。

优先队列的头是基于自然排序或者Comparator排序的最小元素。如果有多个对象拥有同样的排序,那么就可能随机地取其中任意一个。当我们获取队列时,返回队列的头对象。

优先队列的大小是不受限制的,但在创建时可以指定初始大小。当我们向优先队列增加元素的时候,队列大小会自动增加。

Throws exceptionReturns special value
Insertadd(e)offer(e)
Removeremove()poll()
Examineelement()peek()
  1. Constructor()方法。创建一个新的PrioriytQueue
//创建一个新priority queue,默认capacity为11,升序排列
public PriorityQueue<>()
//创建一个新priority queue,默认capacity为initialCapacity
public PriorityQueue<>(int initialCapacity)
//assign comparator
public PriorityQueue<>(int initialCapacity, Comparator<? super E> comparator)
//创建一个包含了collection元素的优先队列。如果是sorted set或另一个priority queue则按照它们的方式排序,否则natural ordering
public PriorityQueue<>(Collection<? extends E> c)
public PriorityQueue<>(SortedSet<? extends E> c)
public PriorityQueue<>(PriorityQueue<? extends E> c)
//eg
PriorityQueue<Integer> pq = new PrioriytQueue<>();
PriorityQueue<Integer> pq = new PrioriytQueue<>(13);
//a simpler comparator format.
PriorityQueue<Integer> pq = new PrioriytQueue<>((a, b) -> b - a);
PriorityQueue<Integer> pq = new PrioriytQueue<>(new Comparator<Integer>(){
	@Override
	public int compare(int a, int b){
		return b - a;
	}
});

//comparator could out of initialization
cmp = new Comparator<Integer>() { 
	public int compare(Integer e1, Integer e2){
		return e2 - e1;
	}};
Queue<Integer> q2 = new PriorityQueue<Integer>(5, cmp);
  1. add()方法。向priority queue中增加一个元素。
public boolean add(E e)
//eg
PriorityQueue<Integer> pq = new PrioriytQueue<>();
pq.add(123);
  1. clear()方法。清除priority queue中的所有元素。queue will be empty after this call return.
public void clear()
//eg
PriorityQueue<Integer> pq = new PrioriytQueue<>();
pq.add(123);
pq.clear();
  1. comparator()方法。返回priority queue使用的comparator,如果没有(natural ordering)返回null。
public Comparator<? super E> comparator()
//eg
PriorityQueue<Integer> pq = new PrioriytQueue<>((a, b) -> b - a);
Comparator<Integer> cmp = pq.comparator();
  1. contains()方法。如果priority queue中含有至少一个传入的object o,返回true。
public boolean contains()
//eg
PriorityQueue<Integer> pq = new PrioriytQueue<>();
pq.add(123);
if (pq.contains(123)){
	//do something
}
  1. iterator()方法。返回一个priority queue的iterator
public Iterator<E> iterator()
//eg
// Creating an empty PriorityQueue 
        PriorityQueue<String> queue = new PriorityQueue<String>(); 
  
        // Use add() method to add elements into the Queue 
        queue.add("Welcome"); 
        queue.add("To"); 
        queue.add("Geeks"); 
        queue.add("4"); 
        queue.add("Geeks"); 
  
        // Displaying the PriorityQueue 
        System.out.println("PriorityQueue: " + queue); 
  
        // Creating an iterator 
        Iterator value = queue.iterator(); 
  
        // Displaying the values after iterating through the queue 
        System.out.println("The iterator values are: "); 
        while (value.hasNext()) { 
            System.out.println(value.next()); 
        } 
  1. offer()方法。插入一个新的元素进入priority queue,如果成功返回true。与Queue类似。
public boolean offer(E e)

//eg
PriorityQueue<Integer> pq = new PrioriytQueue<>();
pq.offer(123);
  1. peek()方法。得到priority queue中的第一个元素,但是不remove。
public E peek()
//eg
PriorityQueue<Integer> pq = new PrioriytQueue<>();
pq.add(123);
int a = pq.peek();
  1. poll()方法。得到并弹出priority queue中的第一个元素
public E poll()
//eg
PriorityQueue<Integer> pq = new PrioriytQueue<>();
pq.offer(123);
int a = pq.poll();
  1. remove()方法。清除priority queue中的第一个元素,如果成功返回true;
public boolean remove()
//eg
PriorityQueue<Integer> pq = new PrioriytQueue<>();
pq.offer(123);
if (pq.remove()){
	//do something
}
  1. size()方法。得到priority queue的大小
public int size()
//eg
PriorityQueue<Integer> pq = new PrioriytQueue<>();
pq.add(123);
int s = pq.size();
  1. toArray()方法。将priority queue转为数组
public Object[] toArray()
public <T> T[] toArray(T[] a)
//eg
// Creating an empty PriorityQueue 
        PriorityQueue<Integer> queue = new PriorityQueue<Integer>(); 
  
        // Use add() method to add elements into the Queue 
        queue.add(10); 
        queue.add(15); 
        queue.add(30); 
        queue.add(20); 
        queue.add(5); 
        queue.add(25); 
  
        // Displaying the PriorityQueue 
        System.out.println("The PriorityQueue: " + queue); 
  
        // Creating the array and using toArray() 
        Object[] arr = queue.toArray(); 
  
        System.out.println("The array is:"); 
        for (int j = 0; j < arr.length; j++) 
            System.out.println(arr[j]); 

/********************************************/
PriorityQueue<String> queue = new PriorityQueue<String>(); 
  
        // Use add() method to add elements into the Queue 
        queue.add("Welcome"); 
        queue.add("To"); 
        queue.add("Geeks"); 
        queue.add("For"); 
        queue.add("Geeks"); 
  
        // Displaying the PriorityQueue 
        System.out.println("The PriorityQueue: " + queue); 
  
        // Creating the array and using toArray() 
        String[] arr = new String[5]; 
        String[] arr1 = queue.toArray(arr); 
          
        // Displaying arr 
        System.out.println("The arr[] is:"); 
        for (int j = 0; j < arr.length; j++) 
            System.out.println(arr[j]); 
          
        // Displaying arr1 
        System.out.println();     
        System.out.println("The arr1[] is:"); 
        for (int i = 0; i < arr1.length; i++) 
            System.out.println(arr1[i]); 

Queue 类

源自于java.util。
队列是一种特殊的线性表,它只允许在表的前端进行删除操作,而在表的后端进行插入操作。

LinkedList类实现了Queue接口,因此我们可以把LinkedList当成Queue来用。Queue接口与List、Set同一级别,都是继承了Collection接口。LinkedList实现了Queue接口。Queue接口窄化了对LinkedList的方法的访问权限(即在方法中的参数类型如果是Queue时,就完全只能访问Queue接口所定义的方法 了,而不能直接访问 LinkedList的非Queue的方法),以使得只有恰当的方法才可以使用.BlockingQueue,Deque等继承了Queue接口。

基于Collection的操作,Queue提供了额外的失败时返回异常的增查改函数,而我们常用的则是返回特定的值(null,false等),后者用于对于Queue大小有要求的情况下,正常来说插入新元素进入Queue是不会失败的。

Throws exceptionReturns special value
Insertadd(e)offer(e)
Removeremove()poll()
Examineelement()peek()
  1. Constructor()方法。创建一个新的Queue
public Queue<T>();
//eg
Queue<Integer> queue = new LinkedList<>();
  1. add()方法。增加一个元素,如果队列已满,则抛出一个IIIegaISlabEepeplian异常
public boolean add(E e)
//eg
Queue<Integer> queue = new LinkedList<>();
boolean empty = queue.add(123);
queue.add(234);
  1. remove()方法。移除并返回队列头部的元素,如果队列为空,则抛出一个NoSuchElementException异常
public E remove()
//eg
Queue<Integer> queue = new LinkedList<>();
int a = queue.remove();
  1. element()方法。返回队列头部的元素,如果队列为空,则抛出一个NoSuchElementException异常
public E element(int index)
//eg
Queue<Integer> queue = new LinkedList<>();
int a = queue.element();
  1. offer()方法。添加一个元素并返回true,如果队列已满,则返回false
public boolean offer(E e)
//eg
Queue<Integer> queue = new LinkedList<>();
queue.offer(123);
  1. poll()方法。移除并返问队列头部的元素 如果队列为空,则返回null
public E poll()
//eg
Queue<Integer> queue = new LinkedList<>();
queue.poll();
  1. peek()方法。返回队列头部的元素,如果队列为空,则返回null
public E peek()
//eg
Queue<Integer> queue = new LinkedList<>();
int a = queue.peek();

Set 接口

源自java.util
Set,集合,注重独一无二的性质,该体系集合可以知道某物是否已近存在于集合中,不会存储重复的元素
用于存储无序(存入和取出的顺序不一定相同)元素,值不能重复。

Set继承于Collection接口,是一个不允许出现重复元素,并且无序的集合,主要有HashSet和TreeSet两大实现类。

在判断重复元素的时候,Set集合会调用hashCode()和equal()方法来实现。

HashSet是哈希表结构,主要利用HashMap的key来存储元素,计算插入元素的hashCode来获取元素在集合中的位置;value是一个固定的Object,相当于阉割版HashMap。

TreeSet是红黑树结构,每一个元素都是树中的一个节点,插入的元素都会进行排序;

方法:

  1. Constructor()方法。创建一个新的set

//eg
//hash set比较常用
Set<Integer> set = new HashSet<>();
Set<Integer> set = new TreeSet<>();
  1. add()方法。向set中添加新元素,如果set中没有这个元素则返回true。
boolean add(E e)
//eg
Set<Integer> set = new HashSet<>();
set.add(233);
  1. clear()方法。清空set
void clear()
//eg
//eg
Set<Integer> set = new HashSet<>();
set.add(233);
set.clear();
  1. contains()方法。判断set是否含有特定的值。
boolean contains(Object o)
//eg
Set<Integer> set = new HashSet<>();
set.add(233);
if (set.contains(233)){
	//do something
}
  1. isEmpty()方法。判断set是否为空
boolean isEmpty()
//eg
Set<Integer> set = new HashSet<>();
set.add(233);
if (set.isEmpty()){
	//do something
}
  1. iterator()方法。返回一个可以遍历set的iterator,顺序是不一定的。
boolean contains(Object o)
//eg
Set hs = new HashSet();
		hs.add("世界军事");
		hs.add("兵器知识");
		hs.add("舰船知识");
		hs.add("汉和防务");
		System.out.println(hs);
		// [舰船知识, 世界军事, 兵器知识, 汉和防务]
		Iterator it = hs.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}
  1. remoev()方法。从set中移除某个元素。如果存在这个元素返回true。
boolean remove(Object o)
//eg
Set<Integer> set = new HashSet<>();
set.add(233);
set.remove(233);
  1. size()方法。返回set大小
int size()
//eg
Set<Integer> set = new HashSet<>();
set.add(233);
int size = set.size();
  1. toArray()方法。将set转为数组返回。
Object[] toArray()
//eg
// Creating a hash set of strings 
        Set<String> s = new HashSet<String>(); 
        s.add("Geeks"); 
        s.add("for"); 
  
        int n = s.size(); 
        String arr[] = new String[n]; 
  
        int i = 0; 
        for (String x : s) 
            arr[i++] = x; 
  
        System.out.println(Arrays.toString(arr)); 
<T> T[] toArray(T[] a)
//eg
// Creating a hash set of strings 
        Set<String> s = new HashSet<String>(); 
        s.add("Geeks"); 
        s.add("for"); 
  
        int n = s.size(); 
        String arr[] = new String[n]; 
  
        // Please refer below post for syntax 
        // details of toArray() 
        // https://www.geeksforgeeks.org/arraylist-array-conversion-java-toarray-methods/ 
        arr = s.toArray(arr); 
  
        System.out.println(Arrays.toString(arr)); 

Stack 类

源自于java.util。
栈是Vector的一个子类,它实现了一个标准的后进先出的栈。

堆栈只定义了默认构造函数,用来创建一个空栈。 堆栈除了包括由Vector定义的所有方法,也定义了自己的一些方法。

  1. Constructor()方法。创建一个新的Stack
public Stack<T>();
//eg
Stack<Integer> stack = new Stack<>();
  1. empty()方法。测试Stack是否为空。别人都是isEmpty(),就是栈特别。
public boolean empty()
//eg
Stack<Integer> stack = new Stack<>();
boolean empty = stack.empty();
  1. peek()方法。查看堆栈顶部的对象,但不从堆栈中移除它。如果Stack为空,会抛出EmptyStackException
public E peek()
//eg
Stack<Integer> stack = new Stack<>();
stack.push(1);
int num = stack.peek();
  1. pop()方法。移除堆栈顶部的对象,并作为此函数的值返回该对象。
public E pop(int index)
//eg
Stack<Integer> stack = new Stack<>();
stack.push(1);
int num = stack.pop();
  1. push()方法。把项压入堆栈顶部。
public E push(int index)
//eg
Stack<Integer> stack = new Stack<>();
stack.push(1);
  1. search()方法。返回对象在堆栈中的位置,以 1 为基数。
public int search(Object o)
//eg
Stack<Integer> stack = new Stack<>();
stack.push(1);
int distance = stack.search(1);

String类

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

**注意:**String 类是不可改变的,所以你一旦创建了 String 对象,那它的值就无法改变了。如果需要对字符串做很多修改,那么应该选择使用 StringBuffer & StringBuilder 类。
菜鸟String

  1. Constructor()方法。创建一个新的String。编译器会使用该值创建一个 String 对象。

和其它对象一样,可以使用关键字和构造方法来创建 String 对象。

String 类有 11 种构造方法,这些方法提供不同的参数来初始化字符串,比如提供一个字符数组参数:

public String()
public StringBuilder(char[])
public StringBuilder(String str)
//eg
String s = "23333"

String s = new String("23333");

char data[] = {'a', 'b', 'c'};
String str = new String(data);
  1. charAt()方法。返回index位置的char。
    An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.
    Throws:
    IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string.
public char charAt(int index)
//eg
String s = "23333";
char ch = s.charAt(2);
  1. compareTo()方法。基于String每个char的Unicode值比较两个String。如果s1比s2在前面,返回负数;如果s1在s2后面,返回正数;如果相同返回0.

This is the definition of lexicographic ordering. If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string. In this case, compareTo returns the difference of the two character values at position k in the two string – that is, the value:

this.charAt(k)-anotherString.charAt(k)

If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings – that is, the value:

this.length()-anotherString.length()

public int compareTo()
//eg
String s1 = "23333";
String s2 = "2333";
int diff = s1.compareTo(s2);
  1. compareToIgnoreCase()方法。忽略大小写的compareTo(),不再赘述。

  2. concat()方法。连接一个新的String在现有String后面。相当于使用“+”连接。

public String concat(String str)
//eg
String s1 = "233";
String s2 = "33";
s1 = s1.concat(s2);
s1 = s1 + s2;
  1. contentEquals()方法。将String与CharSequence或者StringBuffer比较。
public boolean contentEquals(CharSequence cs)
public boolean contentEquals(StringBuffer sb)

//eg

  1. copyValueOf()方法。返回一个由这个char[]组成的String。
    data - the character array.
    offset - initial offset of the subarray.
    count - length of the subarray.
public static String copyValueOf(char[] data)
public static String copyValueOf(char[] data, int offset, int count)
//eg
char[] Str1 = {'h', 'e', 'l', 'l', 'o', ' ', 'r', 'u', 'n', 'o', 'o', 'b'};
String Str2 = "";

Str2 = Str2.copyValueOf( Str1 );

Str2 = Str2.copyValueOf( Str1, 2, 6 );
  1. equals()方法,比较String与传入的object。The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
public boolean equals(Object anObject)
//eg
boolean same = s1.equals(s2);
  1. euqalsIgnoreCase()方法,比较传入的String在忽略大小写情况下是否相同。

Two characters c1 and c2 are considered the same ignoring case if at least one of the following is true:

  • The two characters are the same (as compared by the == operator)
  • Applying the method Character.toUpperCase(char) to each character produces the same result
  • Applying the method Character.toLowerCase(char) to each character produces the same result
public boolean equalsIgnoreCase(String anotherString)
  1. indexOf()方法。返回现在String中,第一次出现输入的char的index。使用fromIndex可以规定开始寻找的范围。注意一定是字符,不是String。
public int indexOf(int ch)
public int indexOf(int ch, int fromIndex)
//eg
String string = "aaa456ac"; 
int index = string.indexOf('b');
index = string.indexOf('a',3)
  1. isEmpty()方法。判断String是否为空
public boolean isEmpty()
  1. lastIndexOf()方法。同理,返回最后一次出现某哥个字符的位置。使用fromIndex可以规定开始寻找的范围。
public int lastIndexOf(int ch)
public int lastIndexOf(int ch, int fromIndex)
//eg
String string = "lastIndexOf"; 
int index = string.lastIndexOf('a');
index = string.lastIndexOf('f',3)
  1. length()方法,返回String的长度。

  2. replace()方法。将String中的字符进行替换,然后返回新的String。

public String replace(char oldChar, char newChar)
public String replace(CharSequence target, CharSequence replacement)
  1. replaceAll()方法,使用正则表达式,匹配替换String中的所有符合pattern的字符。
public String replaceAll(String regex, String replacement)
  1. split()方法。将现在的String根据正则表达式分成多个string数组。可以使用limit限定使用这个pattern的次数,也就是分割产生的份数。
public String[] split(String regex)
public String[] split(String regex, int limit)
//eg
String str = new String("Welcome-to-Runoob");
String[] arr = str.split("-");
String str2 = new String("www.runoob.com");
String[] arr2 = str2.split("\\.");
  1. substring()方法。切割String产生一个新的子字符串,注意是一个单词,不包含endIndex。
public String substring(int beginIndex, int endIndex)
//eg
String str = new String("Welcome-to-Runoob");
String str2 = str.substring(0, str.indexOf('-'));
  1. toUpperCase()方法 && toLowerCase()方法。转换大小写。可以根据指定locale进行转换(不会用)。
public String toLowerCase()
public String toLowerCase(Locale locale)
public String toUpperCase()
public String toUpperCase(Locale locale)

//eg
String str = new String("asbceg");
String str2 = str.toUpperCase();
  1. trim()方法。返回现在String去掉开始和结尾的空格的结果。
public String trim()
//eg
String str = new String("  asbceg  ");
String str2 = str.trim();
  1. valueOf()方法。返回某种参数的字符串形式。
    valueOf() 方法有以下几种不同形式:
  • valueOf(boolean b): 返回 boolean 参数的字符串表示形式。.

  • valueOf(char c): 返回 char 参数的字符串表示形式。

  • valueOf(char[] data): 返回 char 数组参数的字符串表示形式。

  • valueOf(char[] data, int offset, int count): 返回 char 数组参数的特定子数组的字符串表示形式。

  • valueOf(double d): 返回 double 参数的字符串表示形式。

  • valueOf(float f): 返回 float 参数的字符串表示形式。

  • valueOf(int i): 返回 int 参数的字符串表示形式。

  • valueOf(long l): 返回 long 参数的字符串表示形式。

  • valueOf(Object obj): 返回 Object 参数的字符串表示形式。

static String valueOf(boolean b) 
static String valueOf(char c) 
static String valueOf(char[] data) 
static String valueOf(char[] data, int offset, int count) 
static String valueOf(double d) 
static String valueOf(float f) 
static String valueOf(int i)
static String valueOf(long l)
static String valueOf(Object obj) 
//eg
boolean b = true;
String s = String.valueOf(b);

具体例子

StringBuilder类

java.lang库中的类。当对字符串进行修改的时候,需要使用 StringBuffer 和 StringBuilder 类。和 String 类不同的是,StringBuffer 和 StringBuilder 类的对象能够被多次的修改,并且不产生新的未使用对象

StringBuilder 类在 Java 5 中被提出,它和 StringBuffer 之间的最大不同在于 StringBuilder 的方法不是线程安全的(不能同步访问)。但由于 StringBuilder 相较于 StringBuffer 有速度优势,所以多数情况下建议使用 StringBuilder 类。然而在应用程序要求线程安全的情况下,则必须使用 StringBuffer 类。

  1. Constructor()方法。创建一个新的StringBuilder,可以设置初始容量和内容。可以使用String 或者 CharSequence作为初始化内容。
public StringBuilder()
public StringBuilder(int capacity)
public StringBuilder(String str)
public StringBuilder(CharSequence seq)
//eg
StringBuilder sb = new StringBuilder();
//Constructs a string builder with no characters in it and an initial capacity of 16 characters.
StringBuilder sb = new StringBuilder("23333");
StringBuilder sb = new StringBuilder(32);
  1. append()方法。将指定的字符串or whatever追加到此字符序列。append的内容为String.valueOf(T)
public StringBuffer append(T)
//eg
StringBuilder sb = new StringBuilder();
sb.append("233ersansan");
sb.append(true);
sb.append(233);
sb.append(new char[]{'a','b','c'});
sb.append(new StringBuffer("2333"));
sb.append(998.00233);
  1. capacity()方法。返回现在StringBuilder的容量
public int capacity()
//eg
StringBuilder sb = new StringBuilder();
int capacity = sb.capacity();
  1. charAt()方法。返回现在StringBuilder index 位置的char
public char charAt(int index)
//eg
StringBuilder sb = new StringBuilder();
char c = sb.charAt(23);
  1. delete()方法。移除此序列的子字符串中的字符。依然不包括end。
public void delete(int start, int end)
//eg
StringBuilder sb = new StringBuilder("233333");
sb.delete(0, 3);
sb.delete(i, i + 3);//delete a substring start at i with length 3
  1. deleteCharAt()方法。移除此序列中index位置的字符。
public void deleteCharAt(int index)
//eg
StringBuilder sb = new StringBuilder("233333");
sb.deleteCharAt(0);
  1. indexOf()方法。返回现在StringBuilder中,第一次出现输入的substring的index。使用fromIndex可以规定开始寻找的范围。
public int indexOf(String str)
public int indexOf(String str, int fromIndex)
//eg
StringBuilder sb = new StringBuilder("233333");
int index = sb.indexOf("33");
  1. insert()方法。在现在StringBuilder offset 位置插入新内容,offset代表插入第I个元素之前,0 <= offset <= sb.length()。如果插入null,则会插入“null”
public StringBuilder insert(int offset, object T)
public StringBuilder insert(int offset, char[] str)
//eg
StringBuilder sb = new StringBuilder();
sb.insert(0, "233ersansan");
sb.insert(n, true);
sb.insert(sb.length - 233, 233);
sb.insert(2, new char[]{'a','b','c'});
sb.insert(1, 998.00233);
  1. lastIndexOf()方法。返回现在StringBuilder中,最后一次出现输入的substring的index。使用fromIndex可以规定开始寻找的范围。
public int lastIndexOf(String str)
public int lastIndexOf(String str, int fromIndex)
//eg
StringBuilder sb = new StringBuilder();
char c = sb.lastIndexOf(23);
  1. length()方法。返回现在StringBuilder的长度,character count
public int length()
//eg
StringBuilder sb = new StringBuilder("233333");
int len = sb.length()
  1. replace()方法。返回现在StringBuilder index 位置的char
public StringBuilder replace(int start, int end, String str)
//eg
StringBuilder sb = new StringBuilder("233333");
sb.replace(i, i + 3, "233");
  1. reverse()方法。将现在的StringBuilder逆序。
public StringBuilder reverse(int index)
//eg
StringBuilder sb = new StringBuilder("233333");
sb.reverse();
  1. setCharAt()方法。替换StringBuilder index 位置的char为新值
public void setCharAt(int index, char ch)
//eg
StringBuilder sb = new StringBuilder("233333");
sb.setCharAt(3, '2');
  1. subSequence()方法。返回现在StringBuilder从start到end到CharSequence。
public CharSequence subSequence(int start, int end)
//eg
StringBuilder sb = new StringBuilder("233333");
CharSequnce cs = sb.subSequence(0, 3);
  1. substring()方法。返回现在StringBuilder从start到end到String。注意substring是一个单词。
public String substring(int start, int end)
//eg
StringBuilder sb = new StringBuilder("233333");
String s = sb.substring(0, 3);
  1. toString()方法。返回现在StringBuilder的String格式。
public String toString(int index)
//eg
StringBuilder sb = new StringBuilder("234234");
String res = sb.toString();

TreeMap 类

源自于java.util。
在Map集合框架中,除了HashMap以外,TreeMap也是我们工作中常用到的集合对象之一。

与HashMap相比,TreeMap是一个能比较元素大小的Map集合,会对传入的key进行了大小排序。其中,可以使用元素的自然顺序,也可以使用集合中自定义的比较器来进行排序;

不同于HashMap的哈希映射,TreeMap底层实现了树形结构,至于具体形态,你可以简单的理解为一颗倒过来的树—根在上–叶在下。如果用计算机术语来说的话,TreeMap实现了红黑树的结构,形成了一颗二叉树。

在具体使用上,与HashMap类似,但是有一些特殊的用法。
Java集合–TreeMap完全解析
TreeMap official doc

方法:

  1. Constructor()方法。创建一个新的TreeMap

//eg
HashMap<Integer, Integer> map = new HashMap<>();
  1. ceilingKey()方法。返回最接近的大于或等于给定key的key。没有就返回null。
public K ceilingKey(K key)
  1. ceilingEntry()方法。返回最接近的大于或等于给定key的键值对。没有就返回null。
public Map.Entry<K,V> ceilingEntry(K key)

  1. clear()方法。清空TreeMap
public void clear()
  1. descendingKeySet()方法。返回一个map的key set,key是倒序排列的(从大到小)
public NavigableSet<K> descendingKeySet()
  1. descendingMap()方法。返回一个倒序的TreeMap
public NavigableMap<K,V> descendingMap()
//eg
Map<Integer, Integer> map = new HashMap<>();
map.put(1,2);
boolean empty = map.isEmpty();
  1. firstEntry()方法。返回TreeMap的第一个键值对。
public Map.Entry<K,V> firstEntry()
  1. firstKey()方法。返回第一个key
public K firstKey()
  1. floorKey()方法。返回小于key的第一个key
public K floorKey(K key)
  1. headMap()方法。返回一个所有key都小于toKey的map
public SortedMap<K,V> headMap(K toKey)
public NavigableMap<K,V> headMap(K toKey,
                                 boolean inclusive)
  1. higherEntry()方法。返回第一个比key大的entry,没有就返回null。
public Map.Entry<K,V> higherEntry(K key)
  1. higherKey()方法。返回第一个比key大的key,没有就返回null。
public K higherKey(K key)
  1. lastEntry()方法。返回最后一个键值对,如果map空返回null
public Map.Entry<K,V> lastEntry()
  1. lastKey()方法。返回最后一个key,如果map空返回null
public K lastKey()
  1. lowerEntry()方法。返回第一个比key小的entry,没有就返回null。
public Map.Entry<K,V> lowerEntry(K key)
  1. lowerKey()方法。返回第一个比key小的key,没有就返回null。
public K lowerKey(K key)
  1. pollFirstEntry()方法。删除第一个键值对
public Map.Entry<K,V> pollFirstEntry()
  1. pollLastEntry()方法。删除最后一个键值对
public Map.Entry<K,V> pollLastEntry()

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值