|
| 1 | +--- |
| 2 | +Title: 'size()' |
| 3 | +Description: 'Returns the number of elements stored in a queue.' |
| 4 | +Subjects: |
| 5 | + - 'Code Foundations' |
| 6 | + - 'Computer Science' |
| 7 | +Tags: |
| 8 | + - 'Collections' |
| 9 | + - 'Methods' |
| 10 | + - 'Numbers' |
| 11 | + - 'Queues' |
| 12 | +CatalogContent: |
| 13 | + - 'learn-java' |
| 14 | + - 'paths/computer-science' |
| 15 | +--- |
| 16 | + |
| 17 | +In Java, **`size()`** method returns the number of elements currently present in a collection like a queue, helping determine how many items are stored at any given moment. |
| 18 | + |
| 19 | +## Syntax |
| 20 | + |
| 21 | +```pseudo |
| 22 | +queue.size() |
| 23 | +``` |
| 24 | + |
| 25 | +**Parameters:** |
| 26 | + |
| 27 | +The `size()` method does not take any parameters. |
| 28 | + |
| 29 | +**Return value:** |
| 30 | + |
| 31 | +- Returns an integer representing the number of elements in the queue. |
| 32 | + |
| 33 | +## Example 1: Get Queue Length using Java `size()` |
| 34 | + |
| 35 | +In this example, the `size()` method in Java is used to find the number of elements present in a queue: |
| 36 | + |
| 37 | +```java |
| 38 | +import java.util.LinkedList; |
| 39 | +import java.util.Queue; |
| 40 | + |
| 41 | +public class QueueSizeExample { |
| 42 | + public static void main(String[] args) { |
| 43 | + Queue<String> queue = new LinkedList<>(); |
| 44 | + |
| 45 | + queue.add("Apple"); |
| 46 | + queue.add("Banana"); |
| 47 | + queue.add("Cherry"); |
| 48 | + |
| 49 | + System.out.println("Queue size: " + queue.size()); |
| 50 | + } |
| 51 | +} |
| 52 | +``` |
| 53 | + |
| 54 | +The output of this code is: |
| 55 | + |
| 56 | +```shell |
| 57 | +Queue size: 3 |
| 58 | +``` |
| 59 | + |
| 60 | +## Example 2: Check Queue Size Before Processing |
| 61 | + |
| 62 | +In this example, the `size()` method in Java is used to verify if a queue contains elements before processing them: |
| 63 | + |
| 64 | +```java |
| 65 | +import java.util.LinkedList; |
| 66 | +import java.util.Queue; |
| 67 | + |
| 68 | +public class QueueSizeCheckExample { |
| 69 | + public static void main(String[] args) { |
| 70 | + Queue<Integer> numbers = new LinkedList<>(); |
| 71 | + |
| 72 | + numbers.add(10); |
| 73 | + numbers.add(20); |
| 74 | + numbers.add(30); |
| 75 | + |
| 76 | + if (numbers.size() > 0) { |
| 77 | + System.out.println("Queue has " + numbers.size() + " elements. Processing..."); |
| 78 | + while (!numbers.isEmpty()) { |
| 79 | + System.out.println("Removed: " + numbers.remove()); |
| 80 | + } |
| 81 | + } else { |
| 82 | + System.out.println("Queue is empty. Nothing to process."); |
| 83 | + } |
| 84 | + } |
| 85 | +} |
| 86 | +``` |
| 87 | + |
| 88 | +The output of this code is: |
| 89 | + |
| 90 | +```shell |
| 91 | +Queue has 3 elements. Processing... |
| 92 | +Removed: 10 |
| 93 | +Removed: 20 |
| 94 | +Removed: 30 |
| 95 | +``` |
0 commit comments