Java ArrayList Practice Exercises
Java ArrayList Practice Exercises
You can iterate through the list and use the modulus operator to determine if each number is even or odd. For the list [10, 13, 22, 45, 50], the results are 3 even numbers (10, 22, 50) and 2 odd numbers (13, 45).
The approach involves iterating through the ArrayList and using a conditional statement to check if the fruit is "Mango". If it is, print "Found Mango"; otherwise, print "Not Mango". For the list ['Apple', 'Banana', 'Mango', 'Orange'], the output would be "Not Mango", "Not Mango", "Found Mango", "Not Mango" .
Using Java's ArrayList, you can determine the presence of a specific integer using the contains() method. If 15 is checked against the list [5, 10, 15, 20], the outcome is "Found" because 15 is present .
Checking for an element in an ArrayList has a time complexity of O(n) since it may require scanning through all elements. In contrast, HashSet, another structure, provides average O(1) complexity for check operations due to its hashing mechanism, highlighting trade-offs between ArrayList's order retention and HashSet's efficiency .
The method involves iterating over the city list and using a conditional check on the first character. For cities starting with 'D', use a conditional such as city.charAt(0) == 'D'. The cities that meet this condition are 'Delhi', 'Dubai', and 'Detroit' .
Java's ArrayList starts with a default capacity, and when more elements are added beyond this capacity, it dynamically resizes by creating a larger array and copying over the existing elements. This automatic resizing is an internal mechanism that balances additional overhead against flexibility .
The steps involve creating an ArrayList, adding integer values to it using the add() method, and then iterating with a loop to print each element. For the list [10, 20, 35, 40, 55], the expected output is each number printed on a new line: 10, 20, 35, 40, 55 .
Choosing the appropriate data structure is crucial in programming as it impacts efficiency, ease of use, and scalability. ArrayLists in Java provide dynamic arrays, making them ideal for scenarios where the size is not predetermined. They offer flexibility, allowing resizing, easy insertion, and access, which is essential for dynamic data handling .
ArrayLists are preferable when random access is needed due to their O(1) time complexity for get operations. They also facilitate easier iteration and space efficiency, especially when the element length is known. LinkedLists excel in quick insertions and deletions, making ArrayLists better for applications prioritizing access speed .