Skip to content

Commit 00d3121

Browse files
committed
update cheatsheet,
1 parent 70ca5bc commit 00d3121

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

doc/cheatsheet/java_trick.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -933,6 +933,33 @@ PriorityQueue<Map.Entry<Integer, Integer>> heap = new PriorityQueue<>(
933933
// ...
934934
```
935935

936+
### 1-19-2) Queue `add` VS `offer`
937+
938+
- `add(E e)` Method
939+
- Behavior:
940+
- Adds the specified element to the queue.
941+
- If the queue has a capacity restriction and it is full, add() throws an exception (IllegalStateException).
942+
- If the queue allows unlimited elements (like LinkedList), add() behaves similarly to offer() and does not throw an exception.
943+
- Usage:
944+
- Use add() when you want to enforce that the addition must succeed and you want an exception if it fails.
945+
- Return Type:
946+
- Returns true if the element was successfully added.
947+
- Exception Handling:
948+
- Throws an exception if the operation fails due to capacity limits.
949+
950+
951+
- `offer(E e)` Method
952+
- Behavior:
953+
- Adds the specified element to the queue.
954+
- If the queue has a capacity restriction and it is full, offer() returns false instead of throwing an exception.
955+
- It is a more graceful way of adding elements to a queue when capacity may be a concern.
956+
- Usage:
957+
- Use offer() when you want to handle the addition failure more gracefully without relying on exceptions.
958+
- Return Type:
959+
- Returns true if the element was added successfully, and false otherwise.
960+
- Exception Handling:
961+
- Does not throw an exception if the operation fails; returns false instead.
962+
936963
### 1-20) Hashmap return defalut val
937964
```java
938965

leetcode_java/src/main/java/dev/TopoSortTest1.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@ public List<Integer> topoSort(List<List<Integer>> dependencies, int size) throws
7575
for(Integer x: degrees){
7676
if(x==0){
7777
this.queue.add(x);
78+
this.queue.offer(x);
7879
}
7980
}
8081

0 commit comments

Comments
 (0)