Java - 常用数据结构,以及对应接口

  • 栈(Stack):

// 构造方法
Stack<E> stack = new Stack<>();
// 增
E item = stack.push(E item);// 入栈
// 删
E item = stack.pop();// 出栈
// 查
E item = stack.peek();// 查看栈顶元素
int size = stack.size();// 查看栈元素个数
boolean isEmpty = stack.isEmpty();// 判断是否为空
  • 队列(Queue):

// 构造方法
Queue<E> queue = new LinkedList<>();
// 增
boolean success = queue.offer(E item);// 入队
// 删
E item = queue.poll();// 出队
// 查
E item = queue.peek();// 查看队头元素
int size = queue.size();// 查看队元素个数
// 判断
boolean isEmpty = queue.isEmpty();// 判断是否为空
  • 数组(List):(ArrayList & LinkList)

// 构造方法
List<E> list = new LinkedList<>();
List<E> list = new ArrayList<>();
// 增
boolean success  = list.add(E e);// 尾部添加元素
list.add(int index, E e); // 索引添加元素
// 删
boolean success  = list.remove(E e); // 删除元素
E e = list.remove(int index);// 根据索引删除元素
list.clear();// 清空数组 
// 改:
E e = list.set(int index, E e); // 根据索引修改元素
// 查:
E e = list.get(int index);
boolean isEmpty = list.isEmpty();
boolean isContains = list.contains(E e);
  • LinkList:

// 构造方法
LinkedList<E> list = new LinkedList<>();
// 增
list.addFirst(E e);
list.addLast(E e);
boolean success = list.add(E e); // 等价于addLast
// 删
E e = list.removeFirst();
E e = list.removeLast();
E e = list.remove(); // 等价于removeFirst
E e = list.remove(int index);
list.clear();
// 查
E e = list.getFirst();
E e = list.getLast();
E e = list.element(); // 等价于getFirst
boolean contains = list.contains(E e);
int size = list.size();
  • HashMap&Hashtable&TreeMap

// 构造方法
HashMap<K, V> hash = new HashMap<>();
Hashtable<K, V> hash = new Hashtable<>();
TreeMap<K, V> hash = new TreeMap<>();
// 增、改
V value = hash.put(K key, V value);
// 删
V value = hash.remove(K key);
boolean success = hash.remove(K key, V value);
hash.clear();
// 查
V value = hash.get(K key)
boolean isContains = hash.containsKey(K key);
boolean isContains = hash.containsValue(V value);
boolean isEmpty = hash.isEmpty();
int size= hash.size();
  • HashSet

// 构造方法
HashSet<E> set = new HashSet<>();
// 增
boolean success = set.add(E e);
// 删
boolean success = set.remove(E e);
set.clear();
// 查
boolean isContains = set.contains(E e);
boolean isEmpty = set.isEmpty();
int size= set.size();
发布了188 篇原创文章 · 获赞 19 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/songzhuo1991/article/details/104210076