数组
创建&初始化
// 创建指定size的数组
int[] arrs = new int[10];
// 所有默认是0,填充成1
Arrays.fill(arrs, 1);
// 填充已知的数组
int[] arrs = new int[]{1,2,3};
List
排序
算法题中经常出现,根据条件A排序后,再根据条件B排序。使用Comparator.comparing
方法 在使用thenComparing
// 定义student
// 创建并排序
List<Student> list = new ArrayList<Student>(){{
add(new Student(1,2));
add(new Student(3,2));
}};
list.stream().sorted(Comparator.comparing(Student::getAge).thenComparing(Student::getScore));
小技巧,如果比较复杂的排序,可以定义一个新的get方法来处理。
数组list互转
数组转list
Arrays.asList(arrs)
list 转数组
list.stream().toArray(Integer[]::new);
LinkedList
Doubly-linked list implementation of the List and Deque interfaces. Implements all optional list operations, and permits all elements (including null). 又可以当做queue,又可以作为队列
// 队列相关方法
// 获取并移除头节点
public E poll() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
// 添加元素,队尾添加
public boolean offer(E e) {
return add(e);
}
// Queue operations.
/**
* Retrieves, but does not remove, the head (first element) of this list.
*
* @return the head of this list, or {@code null} if this list is empty
* @since 1.5
*/
public E peek() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
// 栈的操作
/**
* Pops an element from the stack represented by this list. In other
* words, removes and returns the first element of this list.
*
* <p>This method is equivalent to {@link #removeFirst()}.
*
* @return the element at the front of this list (which is the top
* of the stack represented by this list)
* @throws NoSuchElementException if this list is empty
* @since 1.6
*/
public E pop() {
return removeFirst();
}
/**
* Pushes an element onto the stack represented by this list. In other
* words, inserts the element at the front of this list.
*
* <p>This method is equivalent to {@link #addFirst}.
*
* @param e the element to push
* @since 1.6
*/
public void push(E e) {
addFirst(e);
}
并且还有get(int index)等list通用的方法。
Map
map作为最常见的算法工具,常用的方法还是要懂
- 记录key的个数,获取key对应的value,如果没有则默认是0
map.getOrDefault(key,0);
- 如果这个0还要再设置进map的value中,则使用computeIfAbsent方法更合适。这样如果map中没有对应key,也会生成一对数据
map.computeIfAbsent(key,k -> 0);
Set
set的底层就是map,主要处理不需要value又需要去重的场景,常用的方法就是put、size。遍历使用iterator或者foreach。
Stack
java提供的栈结构,提供了push pop peek(仅获取顶部的元素,不弹出)
Queue
常用的方法是add和poll。但他是个接口,所以一般使用LinkedList来替代。