天天看點

HashMap,LinkedList,ArrayList常用方法彙總---應對leetcode某些題目

  • HashMap

1、put(K key,V value) 向HashMap集合中添加元素(也稱将鍵(key)/值(value)映射存放到HashMap集合中(注意鍵不能重複)

import java.util.HashMap;
 
public class Test {
 
    public static void main(String[] args) {
	HashMap<String,Integer> map = new HashMap<String,Integer>();
	map.put("Tom", 100);//向map中添加元素key - value
    }
}
           

2、get(Object key) 傳回指定鍵所映射的值,沒有該key對應的值則傳回 null

import java.util.HashMap;
 
public class Test {
 
    public static void main(String[] args) {
	HashMap<String,Integer> map = new HashMap<String,Integer>();
	map.put("Tom", 100);
        int score = map.get("Tom");//擷取鍵“Tom”對應的屬性value值
        System.out.println(score);
    }
}
           

3、size() 傳回HashMap集合中的元素數量

4、clear() 清空HashMap集合

5、isEmpty () 判斷HashMap集合中是否有資料,如果沒有則傳回true,否則傳回false

6、remove(Object key) 删除HashMap集合中鍵為key的資料并傳回其所對應value值

7、values() 傳回HashMap集合中所有value組成的以Collection資料類型格式資料

import java.util.HashMap;
 
public class Test {
 
    public static void main(String[] args) {
	HashMap<String,Integer> map = new HashMap<String,Integer>();
	map.put("Tom", 100);
        map.put("Jim",90);
        Collection<Integer> con = map.values();//将從map集合中擷取的所有value值存放人Collection類型的con集合中
        for(int score : con){
            System.out.println(score);//周遊con集合中的元素
        } 
    }
}
           

8,containsKey(Object key)和containsValue(Object value)是否包含對應的key或者value

  • LinkedList
boolean add(E e) 将指定的元素追加到此清單的末尾
int size() 傳回此清單中的元素數
E get(int index) 傳回此清單中指定位置的元素
E remove(int index) 删除該清單中指定位置的元素
void addFirst(E e) 在該清單開頭插入指定的元素
void addLast(E e) 将指定的元素追加到此清單的末尾
E getFirst() 傳回此清單中的第一個元素
E getLast() 傳回此清單中的最後一個元素
void push(E e) 将元素推送到由此清單表示的堆棧上
E pop() 從此清單表示的堆棧中彈出一個元素

           
  • ArrayList
boolean add(E e) 将指定的元素追加到此清單的末尾
int size() 傳回此清單中的元素個數
E get(int index) 傳回此清單中指定位置的元素
E remove(int index) 删除該清單中指定位置的元素
boolean remove(Object o) 從清單中删除指定元素的第一個出現(如果存在)
boolean contains(Object o) 如果此清單包含指定的元素,則傳回 true
boolean addAll(int index, Collection<? extends E> c) 将指定集合中的所有元素插入到此清單中,從指定的位置開始
- void clear() 從清單中删除所有元素
for / iterator 集合周遊