{"id":23691312,"url":"https://github.com/devnamdev2003/java","last_synced_at":"2025-09-02T20:32:05.030Z","repository":{"id":261219467,"uuid":"883644450","full_name":"devnamdev2003/java","owner":"devnamdev2003","description":null,"archived":false,"fork":false,"pushed_at":"2025-03-01T12:41:33.000Z","size":92686,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-04T00:01:35.573Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://devnamdev2003.github.io/java/","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/devnamdev2003.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-11-05T10:28:09.000Z","updated_at":"2025-03-01T12:41:37.000Z","dependencies_parsed_at":"2024-11-05T11:42:54.963Z","dependency_job_id":"979aea30-3d1e-40b5-8a54-ec347332f942","html_url":"https://github.com/devnamdev2003/java","commit_stats":null,"previous_names":["devnamdev2003/java"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/devnamdev2003/java","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/devnamdev2003%2Fjava","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/devnamdev2003%2Fjava/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/devnamdev2003%2Fjava/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/devnamdev2003%2Fjava/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/devnamdev2003","download_url":"https://codeload.github.com/devnamdev2003/java/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/devnamdev2003%2Fjava/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":273344750,"owners_count":25089039,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-02T02:00:09.530Z","response_time":77,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-12-30T02:56:29.635Z","updated_at":"2025-09-02T20:32:00.008Z","avatar_url":"https://github.com/devnamdev2003.png","language":"Java","funding_links":[],"categories":[],"sub_categories":[],"readme":"# java\n\n- [java](#java)\n  - [Type conversions](#type-conversions)\n    - [1. **Char to Int**](#1-char-to-int)\n    - [2. **Float to Int**](#2-float-to-int)\n    - [3. **Int to Char**](#3-int-to-char)\n    - [4. **Int to Float**](#4-int-to-float)\n    - [5. **Float to String**](#5-float-to-string)\n    - [6. **String to Float**](#6-string-to-float)\n    - [7. **Int to String**](#7-int-to-string)\n    - [4. **String to Int**](#4-string-to-int)\n    - [5. **String to Char**](#5-string-to-char)\n    - [6. **Char to String**](#6-char-to-string)\n  - [Two decimal](#two-decimal)\n    - [1. **Using `String.format`**](#1-using-stringformat)\n    - [2. **Using `System.out.printf`**](#2-using-systemoutprintf)\n    - [3. **Using `Math.round`**](#3-using-mathround)\n    - [4. **Using `BigDecimal` (Precise and Recommended for Calculations)**](#4-using-bigdecimal-precise-and-recommended-for-calculations)\n    - [5. **manually**](#5-manually)\n  - [String](#string)\n    - [The `String` Class in Java](#the-string-class-in-java)\n      - [1. **Initializing Strings**](#1-initializing-strings)\n      - [2. **Insert**](#2-insert)\n      - [3. **Delete**](#3-delete)\n      - [4. **Get**](#4-get)\n      - [5. **Search**](#5-search)\n      - [6. **Iterate**](#6-iterate)\n      - [7. **Size (Length)**](#7-size-length)\n      - [8. **Contains**](#8-contains)\n      - [9. **Clear**](#9-clear)\n      - [10. **isEmpty**](#10-isempty)\n      - [11. **Sort**](#11-sort)\n    - [Additional Helpful String Methods](#additional-helpful-string-methods)\n    - [StringBuilder vs. StringBuffer](#stringbuilder-vs-stringbuffer)\n    - [String Comparison in Java](#string-comparison-in-java)\n  - [ArrayList](#arraylist)\n    - [1. **Default Constructor**](#1-default-constructor)\n    - [2. **Parameterized Constructor (with initial capacity)**](#2-parameterized-constructor-with-initial-capacity)\n    - [3. **Using `Arrays.asList()`**](#3-using-arraysaslist)\n    - [4. **Using `List.of()` (Java 9+)**](#4-using-listof-java-9)\n    - [5. **Using Double-Brace Initialization**](#5-using-double-brace-initialization)\n    - [6. **Using a Stream (Java 8+)**](#6-using-a-stream-java-8)\n    - [7. **Using `Collections.addAll()`**](#7-using-collectionsaddall)\n    - [8. **Using another Collection**](#8-using-another-collection)\n    - [9. **Using `Collections.singletonList()`**](#9-using-collectionssingletonlist)\n    - [10. **Using `addAll()` Method after Initialization**](#10-using-addall-method-after-initialization)\n    - [1. **Insert (Adding Elements)**](#1-insert-adding-elements)\n      - [Methods](#methods)\n      - [Examples](#examples)\n    - [2. **Delete (Removing Elements)**](#2-delete-removing-elements)\n      - [Methods](#methods-1)\n      - [Examples](#examples-1)\n    - [3. **Get (Retrieving Elements)**](#3-get-retrieving-elements)\n      - [Method](#method)\n      - [Example](#example)\n    - [4. **Search (Finding Elements)**](#4-search-finding-elements)\n      - [Methods](#methods-2)\n      - [Example](#example-1)\n    - [5. **Iterate (Looping through Elements)**](#5-iterate-looping-through-elements)\n      - [Methods](#methods-3)\n      - [Example](#example-2)\n    - [6. **Size (Checking Number of Elements)**](#6-size-checking-number-of-elements)\n      - [Method](#method-1)\n      - [Example](#example-3)\n    - [7. **Contains (Checking for Element Existence)**](#7-contains-checking-for-element-existence)\n      - [Example](#example-4)\n    - [8. **Clear (Removing All Elements)**](#8-clear-removing-all-elements)\n      - [Method](#method-2)\n      - [Example](#example-5)\n    - [9. **isEmpty (Checking if List is Empty)**](#9-isempty-checking-if-list-is-empty)\n      - [Example](#example-6)\n    - [10. **Sort (Ordering Elements)**](#10-sort-ordering-elements)\n      - [Example](#example-7)\n    - [Important Considerations with ArrayList](#important-considerations-with-arraylist)\n    - [Conclusion](#conclusion)\n  - [HashMap](#hashmap)\n  - [1. **Initializing a HashMap**](#1-initializing-a-hashmap)\n  - [2. **Inserting Elements into HashMap (`put` Method)**](#2-inserting-elements-into-hashmap-put-method)\n  - [3. **Deleting Elements (`remove` Method)**](#3-deleting-elements-remove-method)\n  - [4. **Retrieving Elements (`get` Method)**](#4-retrieving-elements-get-method)\n  - [5. **Searching for Keys and Values (`containsKey` and `containsValue`)**](#5-searching-for-keys-and-values-containskey-and-containsvalue)\n  - [6. **Iterating Through a HashMap**](#6-iterating-through-a-hashmap)\n    - [Using `forEach` with Lambda Expressions](#using-foreach-with-lambda-expressions)\n    - [Using `entrySet`](#using-entryset)\n    - [Using `keySet` and `values`](#using-keyset-and-values)\n  - [7. **Getting the Size of HashMap (`size` Method)**](#7-getting-the-size-of-hashmap-size-method)\n  - [8. **Checking if HashMap Contains an Element (`contains`)**](#8-checking-if-hashmap-contains-an-element-contains)\n  - [9. **Clearing All Elements (`clear` Method)**](#9-clearing-all-elements-clear-method)\n  - [10. **Checking if HashMap is Empty (`isEmpty` Method)**](#10-checking-if-hashmap-is-empty-isempty-method)\n  - [11. **Sorting a HashMap**](#11-sorting-a-hashmap)\n  - [12. **Handling Collisions in HashMap**](#12-handling-collisions-in-hashmap)\n  - [13. **Fail-Fast Behavior in HashMap**](#13-fail-fast-behavior-in-hashmap)\n  - [14. **Complexity and Performance of HashMap Operations**](#14-complexity-and-performance-of-hashmap-operations)\n  - [15. **Conclusion**](#15-conclusion)\n\n## Type conversions\n\nHere's how you can perform these type conversions in Java:\n\n### 1. **Char to Int**\n\nTo convert a `char` to an `int`, you can simply assign it or cast it to `int`. The ASCII (or Unicode) value of the character will be used as the integer value.\n\n```java\nchar ch = 'A';\nint intValue = ch; // Implicit conversion\n// or\nint intValueExplicit = (int) ch; // Explicit casting\nSystem.out.println(intValue); // Output: 65 (ASCII value of 'A')\n```\n\n### 2. **Float to Int**\n\nTo convert a `float` to an `int`, you need to use casting. This will truncate the decimal portion, so the result will be the integer part only.\n\n```java\nfloat floatValue = 9.99f;\nint intValue = (int) floatValue; // Explicit casting\nSystem.out.println(intValue); // Output: 9\n```\n\n### 3. **Int to Char**\n\nTo convert an `int` to a `char`, you can cast it directly. The integer value will be interpreted as a Unicode (or ASCII) character.\n\n```java\nint intValue = 65;\nchar ch = (char) intValue; // Explicit casting\nSystem.out.println(ch); // Output: 'A' (character with ASCII value 65)\n```\n\n### 4. **Int to Float**\n\nTo convert an `int` to a `float`, you can assign it directly, as this is an implicit widening conversion.\n\n```java\nint intValue = 10;\nfloat floatValue = intValue; // Implicit conversion\nSystem.out.println(floatValue); // Output: 10.0\n```\n\nHere’s how you can perform these conversions in Java:\n\n### 5. **Float to String**\n\n```java\nfloat floatValue = 3.14f;\nString floatToString = Float.toString(floatValue);\n// or\nString floatToString2 = String.valueOf(floatValue);\n```\n\n### 6. **String to Float**\n\n```java\nString str = \"3.14\";\nfloat stringToFloat = Float.parseFloat(str);\n```\n\n### 7. **Int to String**\n\n```java\nint intValue = 42;\nString intToString = Integer.toString(intValue);\n// or\nString intToString2 = String.valueOf(intValue);\n```\n\n### 4. **String to Int**\n\n```java\nString str = \"42\";\nint stringToInt = Integer.parseInt(str);\n```\n\n### 5. **String to Char**\n\nTo get a single character from a string, you can use `charAt(index)`:\n\n```java\nString str = \"Hello\";\nchar stringToChar = str.charAt(0); // gets the first character 'H'\n```\n\n### 6. **Char to String**\n\n```java\nchar ch = 'H';\nString charToString = Character.toString(ch);\n// or\nString charToString2 = String.valueOf(ch);\n```\n\nThese methods will help you convert between these common types easily.\n\n---\n\n## Two decimal\n\nTo convert a float to two decimal places in Java, you can use any of the following methods:\n\n### 1. **Using `String.format`**\n\n```java\nfloat number = 3.14159f;\nString formatted = String.format(\"%.2f\", number);\nSystem.out.println(formatted);  // Output: 3.14\n```\n\n### 2. **Using `System.out.printf`**\n\n```java\nfloat number = 3.14159f;\nSystem.out.printf(\"%.2f\", number);  // Output: 3.14\n```\n\n### 3. **Using `Math.round`**\n\nYou can round the float to two decimal places by multiplying, rounding, and then dividing by 100:\n\n```java\nfloat number = 3.14159f;\nfloat rounded = Math.round(number * 100) / 100f;\nSystem.out.println(rounded);  // Output: 3.14\n```\n\n### 4. **Using `BigDecimal` (Precise and Recommended for Calculations)**\n\n`BigDecimal` is a good choice if you need exact rounding and precision.\n\n```java\nfloat number = 3.14159f;\nBigDecimal bd = new BigDecimal(Float.toString(number));\nbd = bd.setScale(2, RoundingMode.HALF_UP);\nSystem.out.println(bd);  // Output: 3.14\n```\n\n### 5. **manually**\n\n```java\n        float a = sc.nextFloat()*100;\n        int b = (int) a;\n        System.out.println(b/100.00);\n\n```\n\nChoose the method that best fits your needs. If you’re working with financial or high-precision data, `BigDecimal` is generally the best choice.\n\n---\n\n## String\n\nHere's a comprehensive guide on initializing and using the `String` class in Java, along with an explanation of relevant methods such as `insert`, `delete`, `get`, `search`, `iterate`, `size`, `contains`, `clear`, `isEmpty`, and `sort`. I'll cover each operation in detail and how it applies to strings in Java, totaling over 1000 words.\n\n---\n\n### The `String` Class in Java\n\nIn Java, `String` is a built-in class that represents a sequence of characters. Strings are objects, not primitive types, and are immutable. Once created, the characters of a string cannot be changed. This immutability provides advantages, such as thread safety, but also requires extra care when performing operations that might alter the content of a `String`. For situations requiring modification, Java provides classes like `StringBuilder` and `StringBuffer`.\n\n#### 1. **Initializing Strings**\n\n- **Direct Assignment**: A string can be initialized directly using quotes, e.g., `String str = \"Hello, World!\";`.\n- **Using `new` Keyword**: Alternatively, you can use the `new` keyword: `String str = new String(\"Hello, World!\");`.\n- **Empty String**: You can initialize an empty string as `String str = \"\";`.\n- **From Character Array**: Convert an array to a string: `String str = new String(charArray);`.\n\n#### 2. **Insert**\n\nSince `String` objects are immutable, Java doesn't provide a direct `insert` method for `String`. However, if you need to insert text at a specific index within a string, you can use `StringBuilder`, which allows modifications.\n\n```java\nStringBuilder builder = new StringBuilder(\"Hello!\");\nbuilder.insert(5, \", World\");\nString result = builder.toString(); // Result: \"Hello, World!\"\n```\n\n#### 3. **Delete**\n\nSimilarly, the `String` class lacks a `delete` method. But with `StringBuilder`, you can delete characters at specified indices.\n\n```java\nStringBuilder builder = new StringBuilder(\"Hello, World!\");\nbuilder.delete(5, 7); // Deletes \", \"\nString result = builder.toString(); // Result: \"HelloWorld!\"\n```\n\n#### 4. **Get**\n\nThe `String` class has several methods to access characters:\n\n- **`charAt(int index)`**: Returns the character at the specified index.\n- **`substring(int beginIndex, int endIndex)`**: Returns a part of the string as a new string, from `beginIndex` (inclusive) to `endIndex` (exclusive).\n\nExample:\n\n```java\nString str = \"Hello, World!\";\nchar ch = str.charAt(1); // 'e'\nString subStr = str.substring(0, 5); // \"Hello\"\n```\n\n#### 5. **Search**\n\nThere are several ways to search within a `String`:\n\n- **`indexOf(String str)`**: Returns the index of the first occurrence of the specified substring. If not found, it returns `-1`.\n- **`lastIndexOf(String str)`**: Returns the index of the last occurrence of the specified substring.\n- **`contains(CharSequence s)`**: Returns `true` if the string contains the specified sequence of characters.\n\n```java\nString str = \"Hello, World!\";\nint index = str.indexOf(\"World\"); // 7\nboolean containsWorld = str.contains(\"World\"); // true\n```\n\n#### 6. **Iterate**\n\nIterating over a `String` is commonly done in two ways:\n\n- **Using `charAt`**: Access each character by its index.\n- **Convert to `char` array**: Use `toCharArray()` to get a `char` array and iterate.\n\n```java\nString str = \"Hello\";\nfor (int i = 0; i \u003c str.length(); i++) {\n    System.out.print(str.charAt(i) + \" \");\n}\n\n// Or using toCharArray\nfor (char c : str.toCharArray()) {\n    System.out.print(c + \" \");\n}\n```\n\n#### 7. **Size (Length)**\n\nThe `length()` method in `String` returns the number of characters in the string. This is the equivalent of `size` in other collections.\n\n```java\nString str = \"Hello, World!\";\nint length = str.length(); // 13\n```\n\n#### 8. **Contains**\n\nThe `contains` method checks if a `String` contains a specific sequence of characters.\n\n```java\nString str = \"Hello, World!\";\nboolean containsHello = str.contains(\"Hello\"); // true\n```\n\n#### 9. **Clear**\n\nWhile `String` is immutable, you can “clear” it by reassigning an empty string to it.\n\n```java\nString str = \"Hello, World!\";\nstr = \"\"; // Clear the content\n```\n\nIn mutable contexts, you may choose `StringBuilder` for a `clear`-like operation by setting its length to `0`.\n\n```java\nStringBuilder builder = new StringBuilder(\"Hello, World!\");\nbuilder.setLength(0); // Clears the content\n```\n\n#### 10. **isEmpty**\n\nThe `isEmpty()` method checks if a string is empty (i.e., has no characters, `length() == 0`).\n\n```java\nString str = \"\";\nboolean isEmpty = str.isEmpty(); // true\n```\n\n#### 11. **Sort**\n\nSorting a string means rearranging its characters in a specific order, typically alphabetical. This is not a direct method on `String` but can be achieved by converting the string to a character array, sorting it, and creating a new string.\n\n```java\nString str = \"edcba\";\nchar[] charArray = str.toCharArray();\nArrays.sort(charArray);\nString sortedStr = new String(charArray); // \"abcde\"\n```\n\n### Additional Helpful String Methods\n\n- **`equals(String str)`** and **`equalsIgnoreCase(String str)`**: Check if two strings are equal or equal regardless of case.\n- **`toUpperCase()`** and **`toLowerCase()`**: Convert all characters to uppercase or lowercase.\n- **`trim()`**: Removes leading and trailing whitespace.\n- **`replace(CharSequence target, CharSequence replacement)`**: Replaces all occurrences of a substring.\n\n### StringBuilder vs. StringBuffer\n\nFor mutable strings, Java provides `StringBuilder` and `StringBuffer` classes, with `StringBuilder` being faster but not thread-safe, while `StringBuffer` is thread-safe.\n\n### String Comparison in Java\n\nString comparison in Java can be done using `equals` for exact matches or `compareTo` for lexicographical order.\n\n```java\nString a = \"Apple\";\nString b = \"Banana\";\nint result = a.compareTo(b); // Negative if a \u003c b, zero if a == b, positive if a \u003e b\n```\n\n---\n\nThe `String` class in Java is foundational, and understanding these methods is essential for efficient and effective text manipulation in Java applications. Since strings are immutable, modifying a `String` often requires reassignment, or you can use `StringBuilder` for cases where mutability is needed.\n\n---\n\n## ArrayList\n\nIn Java, there are several ways to initialize an `ArrayList`. Each approach varies depending on the situation and requirements, offering flexibility in how elements are added to the list. Here’s a rundown of the most common methods to initialize an `ArrayList`.\n\n### 1. **Default Constructor**\n\nThis is the most straightforward way to initialize an empty `ArrayList`.\n\n```java\nArrayList\u003cString\u003e list = new ArrayList\u003c\u003e();\n```\n\n### 2. **Parameterized Constructor (with initial capacity)**\n\nYou can initialize an `ArrayList` with a specified initial capacity. This is helpful if you know the approximate number of elements the list will contain, as it reduces the need for resizing.\n\n```java\nArrayList\u003cString\u003e list = new ArrayList\u003c\u003e(10); // Initial capacity of 10\n```\n\n### 3. **Using `Arrays.asList()`**\n\nYou can initialize an `ArrayList` with a predefined list of elements using `Arrays.asList()`. However, this will return a fixed-size list, so you can't add or remove elements from it without creating a new list.\n\n```java\nArrayList\u003cString\u003e list = new ArrayList\u003c\u003e(Arrays.asList(\"Apple\", \"Banana\", \"Grapes\"));\n```\n\n### 4. **Using `List.of()` (Java 9+)**\n\nIntroduced in Java 9, `List.of()` allows you to create an immutable list with elements. You can then pass this immutable list to an `ArrayList` constructor to get a mutable list with predefined elements.\n\n```java\nArrayList\u003cString\u003e list = new ArrayList\u003c\u003e(List.of(\"Apple\", \"Banana\", \"Grapes\"));\n```\n\n### 5. **Using Double-Brace Initialization**\n\nThis approach uses an anonymous inner class to initialize the `ArrayList`. Although concise, it’s generally discouraged due to performance and memory overhead.\n\n```java\nArrayList\u003cString\u003e list = new ArrayList\u003cString\u003e() {{\n    add(\"Apple\");\n    add(\"Banana\");\n    add(\"Grapes\");\n}};\n```\n\n### 6. **Using a Stream (Java 8+)**\n\nYou can use Java 8 Streams to initialize an `ArrayList` by collecting stream elements.\n\n```java\nArrayList\u003cString\u003e list = Stream.of(\"Apple\", \"Banana\", \"Grapes\")\n                               .collect(Collectors.toCollection(ArrayList::new));\n```\n\n### 7. **Using `Collections.addAll()`**\n\n`Collections.addAll()` is a convenient way to initialize an `ArrayList` with multiple elements.\n\n```java\nArrayList\u003cString\u003e list = new ArrayList\u003c\u003e();\nCollections.addAll(list, \"Apple\", \"Banana\", \"Grapes\");\n```\n\n### 8. **Using another Collection**\n\nIf you already have another collection (like a `Set` or another `List`), you can initialize an `ArrayList` with its elements.\n\n```java\nList\u003cString\u003e existingList = List.of(\"Apple\", \"Banana\", \"Grapes\");\nArrayList\u003cString\u003e list = new ArrayList\u003c\u003e(existingList);\n```\n\n### 9. **Using `Collections.singletonList()`**\n\n`Collections.singletonList()` creates a one-element list, which can then be used to initialize an `ArrayList`. Note that `Collections.singletonList()` itself returns an immutable list, so it's passed as an argument to create a mutable `ArrayList`.\n\n```java\nArrayList\u003cString\u003e list = new ArrayList\u003c\u003e(Collections.singletonList(\"Apple\"));\n```\n\n### 10. **Using `addAll()` Method after Initialization**\n\nAnother way to populate an `ArrayList` after initialization is by using the `addAll()` method. This can be done either from another collection or directly using `Arrays.asList()`.\n\n```java\nArrayList\u003cString\u003e list = new ArrayList\u003c\u003e();\nlist.addAll(Arrays.asList(\"Apple\", \"Banana\", \"Grapes\"));\n```\n\nAn `ArrayList` in Java is a resizable array implementation in the `java.util` package, which offers a flexible, easy-to-use alternative to traditional arrays. It is part of Java's `List` interface and provides several powerful methods to handle elements dynamically, making it a popular choice when the number of elements in a list changes frequently. Here’s a detailed look at how to use `ArrayList` with various methods and operations, such as `insert`, `delete`, `get`, `search`, `iterate`, `size`, `contains`, `clear`, `isEmpty`, and `sort`.\n\n### 1. **Insert (Adding Elements)**\n\nInserting elements into an `ArrayList` is straightforward, thanks to methods like `add()`:\n\n#### Methods\n\n- **`add(E element)`**: Adds the specified element to the end of the `ArrayList`.\n- **`add(int index, E element)`**: Inserts the specified element at the specified position.\n\n#### Examples\n\n```java\nArrayList\u003cString\u003e list = new ArrayList\u003c\u003e();\nlist.add(\"Apple\"); // Adds \"Apple\" at the end\nlist.add(\"Banana\"); // Adds \"Banana\" at the end\n\nlist.add(1, \"Grapes\"); // Inserts \"Grapes\" at index 1\nSystem.out.println(list); // Output: [Apple, Grapes, Banana]\n```\n\nThe `add()` method shifts elements to accommodate the new element at the specified index, if given.\n\n### 2. **Delete (Removing Elements)**\n\nRemoving elements from an `ArrayList` can be done by index or by specifying the object.\n\n#### Methods\n\n- **`remove(int index)`**: Removes the element at the specified index.\n- **`remove(Object obj)`**: Removes the first occurrence of the specified element.\n\n#### Examples\n\n```java\nArrayList\u003cString\u003e list = new ArrayList\u003c\u003e();\nlist.add(\"Apple\");\nlist.add(\"Banana\");\nlist.add(\"Grapes\");\n\nlist.remove(1); // Removes \"Banana\"\nSystem.out.println(list); // Output: [Apple, Grapes]\n\nlist.remove(\"Apple\"); // Removes \"Apple\" by element\nSystem.out.println(list); // Output: [Grapes]\n```\n\nUsing the `remove(int index)` shifts subsequent elements to the left, reducing the list's size by one.\n\n### 3. **Get (Retrieving Elements)**\n\nRetrieving elements at a specific index in `ArrayList` is handled by the `get()` method.\n\n#### Method\n\n- **`get(int index)`**: Returns the element at the specified position.\n\n#### Example\n\n```java\nArrayList\u003cString\u003e list = new ArrayList\u003c\u003e();\nlist.add(\"Apple\");\nlist.add(\"Banana\");\nlist.add(\"Grapes\");\n\nString fruit = list.get(1); // Retrieves \"Banana\"\nSystem.out.println(fruit); // Output: Banana\n```\n\nAttempting to access an out-of-bounds index will throw an `IndexOutOfBoundsException`.\n\n### 4. **Search (Finding Elements)**\n\nTo search for elements in an `ArrayList`, you can use `contains()` or `indexOf()`.\n\n#### Methods\n\n- **`contains(Object obj)`**: Checks if the list contains the specified element.\n- **`indexOf(Object obj)`**: Returns the index of the first occurrence of the specified element, or -1 if the element is not found.\n\n#### Example\n\n```java\nArrayList\u003cString\u003e list = new ArrayList\u003c\u003e();\nlist.add(\"Apple\");\nlist.add(\"Banana\");\n\nboolean hasApple = list.contains(\"Apple\"); // true\nint index = list.indexOf(\"Banana\"); // 1\n\nSystem.out.println(hasApple); // Output: true\nSystem.out.println(index); // Output: 1\n```\n\n### 5. **Iterate (Looping through Elements)**\n\nJava provides multiple ways to iterate through an `ArrayList`.\n\n#### Methods\n\n- **`for` loop**: Use a basic for loop with `get(int index)`.\n- **Enhanced `for` loop**: Easier syntax, especially for collections.\n- **Iterator**: Provides more control over elements with `Iterator` methods.\n\n#### Example\n\n```java\nArrayList\u003cString\u003e list = new ArrayList\u003c\u003e();\nlist.add(\"Apple\");\nlist.add(\"Banana\");\nlist.add(\"Grapes\");\n\n// Using basic for loop\nfor (int i = 0; i \u003c list.size(); i++) {\n    System.out.println(list.get(i));\n}\n\n// Using enhanced for loop\nfor (String fruit : list) {\n    System.out.println(fruit);\n}\n\n// Using Iterator\nIterator\u003cString\u003e iterator = list.iterator();\nwhile (iterator.hasNext()) {\n    System.out.println(iterator.next());\n}\n```\n\n### 6. **Size (Checking Number of Elements)**\n\nThe `size()` method returns the number of elements in an `ArrayList`.\n\n#### Method\n\n- **`size()`**: Returns the number of elements in the list.\n\n#### Example\n\n```java\nArrayList\u003cString\u003e list = new ArrayList\u003c\u003e();\nlist.add(\"Apple\");\nlist.add(\"Banana\");\n\nSystem.out.println(list.size()); // Output: 2\n```\n\n### 7. **Contains (Checking for Element Existence)**\n\nThe `contains()` method is used to check if an element exists in the list.\n\n#### Example\n\n```java\nArrayList\u003cString\u003e list = new ArrayList\u003c\u003e();\nlist.add(\"Apple\");\n\nboolean exists = list.contains(\"Apple\"); // true\nSystem.out.println(exists); // Output: true\n```\n\n### 8. **Clear (Removing All Elements)**\n\nThe `clear()` method removes all elements from the list, effectively making it empty.\n\n#### Method\n\n- **`clear()`**: Removes all elements from the list.\n\n#### Example\n\n```java\nArrayList\u003cString\u003e list = new ArrayList\u003c\u003e();\nlist.add(\"Apple\");\nlist.add(\"Banana\");\n\nlist.clear();\nSystem.out.println(list.size()); // Output: 0\nSystem.out.println(list); // Output: []\n```\n\n### 9. **isEmpty (Checking if List is Empty)**\n\nThe `isEmpty()` method checks if the list contains any elements.\n\n#### Example\n\n```java\nArrayList\u003cString\u003e list = new ArrayList\u003c\u003e();\nSystem.out.println(list.isEmpty()); // true\n\nlist.add(\"Apple\");\nSystem.out.println(list.isEmpty()); // false\n```\n\n### 10. **Sort (Ordering Elements)**\n\nSorting in an `ArrayList` can be done using `Collections.sort()` for natural ordering or a custom `Comparator`.\n\n#### Example\n\n```java\nArrayList\u003cString\u003e list = new ArrayList\u003c\u003e();\nlist.add(\"Banana\");\nlist.add(\"Apple\");\nlist.add(\"Grapes\");\n\nCollections.sort(list);\nSystem.out.println(list); // Output: [Apple, Banana, Grapes]\n\n// Custom sorting\nCollections.sort(list, Collections.reverseOrder());\nSystem.out.println(list); // Output: [Grapes, Banana, Apple]\n```\n\n### Important Considerations with ArrayList\n\n- **Capacity Management**: Internally, an `ArrayList` maintains an array that grows dynamically, which incurs a slight overhead during resizing operations.\n- **Performance**: Since `ArrayList` allows random access with constant time complexity `O(1)`, it is efficient for accessing elements. However, inserting and deleting at arbitrary positions may take longer due to shifting.\n- **Null Elements**: `ArrayList` can store `null` elements. Be cautious when handling lists with nulls, as this can lead to `NullPointerException`.\n\n### Conclusion\n\nThe `ArrayList` class is a flexible and powerful data structure in Java, offering a variety of methods for efficient storage, retrieval, and manipulation of data.\n\n---\n\n## HashMap\n\nThe `HashMap` class in Java is one of the most commonly used data structures in the Java Collections Framework (JCF). It provides a way to store and retrieve key-value pairs and operates on the principle of hashing. With a `HashMap`, you can store data in key-value format, which enables fast access, insertion, and deletion based on unique keys. Let’s dive deep into each of the essential operations provided by the `HashMap` class, including its initialization, methods for data manipulation, retrieval, and common operations like checking its size or whether it is empty.\n\n## 1. **Initializing a HashMap**\n\nTo create a `HashMap`, you use the constructor to instantiate a new object of this class. Java provides a few constructors that let you initialize a `HashMap` with default settings or with custom initial capacities and load factors. Here’s how you can initialize a `HashMap`:\n\n```java\nimport java.util.HashMap;\n\npublic class HashMapExample {\n    public static void main(String[] args) {\n        // Basic initialization\n        HashMap\u003cString, Integer\u003e map = new HashMap\u003c\u003e();\n\n        // Initializing with specified initial capacity and load factor\n        HashMap\u003cString, Integer\u003e customMap = new HashMap\u003c\u003e(16, 0.75f);\n    }\n}\n```\n\nThe `initial capacity` specifies the number of buckets in the hash table, and the `load factor` is a measure of how full the `HashMap` can get before its capacity is automatically increased. The default load factor is 0.75, meaning that when the map reaches 75% of its capacity, it will resize.\n\n## 2. **Inserting Elements into HashMap (`put` Method)**\n\nThe `put` method in `HashMap` allows you to add new key-value pairs or update the value of an existing key. Here’s how you use it:\n\n```java\nmap.put(\"Apple\", 10);\nmap.put(\"Banana\", 20);\nmap.put(\"Cherry\", 30);\n```\n\nIf the key already exists, `put` will update the key with the new value, and it will return the old value. If the key does not exist, it will add a new entry to the map.\n\n## 3. **Deleting Elements (`remove` Method)**\n\nThe `remove` method lets you delete key-value pairs based on the key. It returns the value associated with the key that was removed or `null` if the key does not exist.\n\n```java\n// Removing an element by key\nmap.remove(\"Banana\");\n```\n\nYou can also specify both the key and the value in the `remove` method. This variation will only remove the key if the value matches the specified value.\n\n```java\nmap.remove(\"Cherry\", 30);\n```\n\n## 4. **Retrieving Elements (`get` Method)**\n\nThe `get` method allows you to retrieve the value associated with a specific key. If the key is not present, `get` returns `null`.\n\n```java\nint appleCount = map.get(\"Apple\"); // returns 10\n```\n\nYou can also use `getOrDefault` if you want to specify a default value that should be returned when the key is not present:\n\n```java\nint mangoCount = map.getOrDefault(\"Mango\", 0); // returns 0 if \"Mango\" is not found\n```\n\n## 5. **Searching for Keys and Values (`containsKey` and `containsValue`)**\n\nThe `containsKey` method checks if a specific key exists in the `HashMap`, while `containsValue` checks for the presence of a specific value.\n\n```java\nboolean hasApple = map.containsKey(\"Apple\"); // returns true\nboolean hasFifty = map.containsValue(50);    // returns false\n```\n\n## 6. **Iterating Through a HashMap**\n\nThere are multiple ways to iterate through a `HashMap`. Some of the common ways are:\n\n### Using `forEach` with Lambda Expressions\n\n```java\nmap.forEach((key, value) -\u003e System.out.println(key + \" -\u003e \" + value));\n```\n\n### Using `entrySet`\n\n```java\nfor (Map.Entry\u003cString, Integer\u003e entry : map.entrySet()) {\n    System.out.println(entry.getKey() + \" -\u003e \" + entry.getValue());\n}\n```\n\n### Using `keySet` and `values`\n\nTo iterate through only the keys:\n\n```java\nfor (String key : map.keySet()) {\n    System.out.println(\"Key: \" + key);\n}\n```\n\nTo iterate through only the values:\n\n```java\nfor (Integer value : map.values()) {\n    System.out.println(\"Value: \" + value);\n}\n```\n\n## 7. **Getting the Size of HashMap (`size` Method)**\n\nThe `size` method returns the number of key-value pairs in the `HashMap`.\n\n```java\nint size = map.size(); // returns the size of the map\n```\n\n## 8. **Checking if HashMap Contains an Element (`contains`)**\n\n`HashMap` does not directly have a `contains` method, but it provides `containsKey` and `containsValue` as mentioned above.\n\n## 9. **Clearing All Elements (`clear` Method)**\n\nThe `clear` method removes all elements from the `HashMap`. After calling `clear`, the `HashMap` will be empty, with a size of 0.\n\n```java\nmap.clear(); // removes all entries\n```\n\n## 10. **Checking if HashMap is Empty (`isEmpty` Method)**\n\nThe `isEmpty` method checks if there are any entries in the `HashMap`. It returns `true` if the map is empty, and `false` otherwise.\n\n```java\nboolean empty = map.isEmpty(); // returns true if map is empty\n```\n\n## 11. **Sorting a HashMap**\n\nSince `HashMap` does not maintain order, you cannot directly sort it. If you want to sort by keys or values, you can use a `TreeMap` (for natural key order) or sort the entries using Java Streams. Here’s how to sort a `HashMap` by keys:\n\n```java\nimport java.util.Map;\nimport java.util.TreeMap;\n\nHashMap\u003cString, Integer\u003e map = new HashMap\u003c\u003e();\nmap.put(\"Banana\", 20);\nmap.put(\"Apple\", 10);\nmap.put(\"Cherry\", 30);\n\nMap\u003cString, Integer\u003e sortedMap = new TreeMap\u003c\u003e(map);\n```\n\nOr, to sort by values, you can use streams:\n\n```java\nmap.entrySet().stream()\n    .sorted(Map.Entry.comparingByValue())\n    .forEach(entry -\u003e System.out.println(entry.getKey() + \" -\u003e \" + entry.getValue()));\n```\n\n## 12. **Handling Collisions in HashMap**\n\nJava’s `HashMap` uses separate chaining and tree-binning techniques to resolve collisions (when two keys hash to the same bucket). When the number of entries in a bucket exceeds a threshold, it is converted from a linked list to a balanced tree, which improves performance for large numbers of collisions.\n\n## 13. **Fail-Fast Behavior in HashMap**\n\nA `HashMap` is fail-fast, which means that if you try to modify the map while iterating through it (e.g., by using `put` or `remove`), a `ConcurrentModificationException` is thrown. This happens because `HashMap` uses a `modCount` variable to keep track of structural changes, ensuring safe iteration.\n\n```java\nfor (Map.Entry\u003cString, Integer\u003e entry : map.entrySet()) {\n    if (entry.getKey().equals(\"Banana\")) {\n        map.remove(\"Banana\"); // Throws ConcurrentModificationException\n    }\n}\n```\n\nTo safely remove elements while iterating, use an `Iterator`:\n\n```java\nIterator\u003cMap.Entry\u003cString, Integer\u003e\u003e iterator = map.entrySet().iterator();\nwhile (iterator.hasNext()) {\n    Map.Entry\u003cString, Integer\u003e entry = iterator.next();\n    if (entry.getKey().equals(\"Banana\")) {\n        iterator.remove(); // Safe removal\n    }\n}\n```\n\n## 14. **Complexity and Performance of HashMap Operations**\n\nThe average time complexity of a `HashMap` is as follows:\n\n- **Insertion (`put`)**: \\(O(1)\\) on average, \\(O(n)\\) in the worst case (during resizing).\n- **Retrieval (`get`)**: \\(O(1)\\) on average.\n- **Deletion (`remove`)**: \\(O(1)\\) on average.\n\nIn practice, `HashMap` is highly efficient for most scenarios, but performance can degrade if there are too many hash collisions.\n\n## 15. **Conclusion**\n\nIn summary, `HashMap` in Java is a highly versatile and efficient data structure that enables the storage and retrieval of key-value pairs with optimal performance. Through methods like `put`, `get`, `remove`, `containsKey`, and others, it provides flexible and powerful mechanisms to handle data in a way that supports fast access and modification. However, be mindful of its fail-fast behavior and the potential need to handle sorting and collisions effectively.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdevnamdev2003%2Fjava","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdevnamdev2003%2Fjava","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdevnamdev2003%2Fjava/lists"}