Skip to content

Commit 370723f

Browse files
[Term Entry] Java Queue: .element()
* New Entry : java queue element() method term entry * minor fixes * Minor changes ---------
1 parent 188d3cf commit 370723f

File tree

1 file changed

+81
-0
lines changed
  • content/java/concepts/queue/terms/element

1 file changed

+81
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
---
2+
Title: '.element()'
3+
Description: 'Returns the head of the queue without removing it.'
4+
Subjects:
5+
- 'Code Foundations'
6+
- 'Computer Science'
7+
Tags:
8+
- 'Collections'
9+
- 'Data Structures'
10+
- 'Methods'
11+
- 'Queues'
12+
CatalogContent:
13+
- 'learn-java'
14+
- 'paths/computer-science'
15+
---
16+
17+
In Java, the **`.element()`** method of the `Queue` interface retrieves, but does not remove, the head of the queue. Unlike `.peek()`, which returns null if the queue is empty, `.element()` throws a `NoSuchElementException` in such cases. This method provides a way to inspect the next element to be removed without modifying the queue's structure.
18+
19+
## Syntax
20+
21+
```pseudo
22+
queueName.element()
23+
```
24+
25+
**Parameters:**
26+
27+
The `.element()` method does not take any parameters.
28+
29+
**Return value:**
30+
31+
- Returns the head element of the queue.
32+
- Throws `NoSuchElementException` if the queue is empty.
33+
34+
## Example
35+
36+
This example demonstrates the `.element()` method with a `LinkedList` implementation of `Queue`:
37+
38+
```java
39+
import java.util.LinkedList;
40+
import java.util.Queue;
41+
import java.util.NoSuchElementException;
42+
43+
44+
public class Main {
45+
public static void main(String[] args) {
46+
Queue<String> animals = new LinkedList<String>();
47+
48+
// Add elements to the queue
49+
animals.offer("Dog");
50+
animals.offer("Cat");
51+
animals.offer("Bird");
52+
53+
// Use .element() to peek at the head without removing it
54+
System.out.println("Head element: " + animals.element());
55+
System.out.println("Queue after element(): " + animals);
56+
57+
// Remove elements and check head
58+
animals.poll();
59+
System.out.println("Head after poll: " + animals.element());
60+
61+
// Clear the queue
62+
animals.clear();
63+
64+
// Attempting to use .element() on empty queue throws exception
65+
try {
66+
animals.element();
67+
} catch (NoSuchElementException e) {
68+
System.out.println("Exception: Queue is empty!");
69+
}
70+
}
71+
}
72+
```
73+
74+
Here is the output:
75+
76+
```shell
77+
Head element: Dog
78+
Queue after element(): [Dog, Cat, Bird]
79+
Head after poll: Cat
80+
Exception: Queue is empty!
81+
```

0 commit comments

Comments
 (0)