0% found this document useful (0 votes)
28 views4 pages

Java ArrayList Operations and Examples

This document discusses Java code examples for working with ArrayLists and arrays. It includes code to: 1. Convert an ArrayList to an array by iterating through the ArrayList and adding each element to the array. 2. Sort an ArrayList in ascending or descending order using the Collections.sort() and Collections.reverse() methods. 3. Find the minimum and maximum elements of an integer array using Collections.min() and Collections.max(). 4. Perform time conversion that takes in a time in 12-hour format and prints it in 24-hour format. 5. Modify an array to calculate the running sum of prior elements in each index.

Uploaded by

Islamic India
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views4 pages

Java ArrayList Operations and Examples

This document discusses Java code examples for working with ArrayLists and arrays. It includes code to: 1. Convert an ArrayList to an array by iterating through the ArrayList and adding each element to the array. 2. Sort an ArrayList in ascending or descending order using the Collections.sort() and Collections.reverse() methods. 3. Find the minimum and maximum elements of an integer array using Collections.min() and Collections.max(). 4. Perform time conversion that takes in a time in 12-hour format and prints it in 24-hour format. 5. Modify an array to calculate the running sum of prior elements in each index.

Uploaded by

Islamic India
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

ArrayList

ArrayList<Integer> arrli = new ArrayList<Integer>(n);

 [Link](i);

[Link](3);

[Link](i)
// Java program to convert a ArrayList to an array
// using get() in a loop.
import [Link].*;
import [Link];
import [Link];
  
class GFG
{
    public static void main (String[] args)
    {
        List<Integer> al = new ArrayList<Integer>();
        [Link](10);
        [Link](20);
        [Link](30);
        [Link](40);
  
        Integer[] arr = new Integer[[Link]()];
  
        // ArrayList to Array Conversion
        for (int i =0; i < [Link](); i++)
            arr[i] = [Link](i);
  
        for (Integer x : arr)
            [Link](x + " ");
    }
}

[Link](list);// ArrayList in ascending order


[Link](list);//ArrayList in descending

// creating Arrays of String type


            String a[] = new String[] { "A", "B", "C", "D" };
  
            // getting the list view of Array
            List<String> list = [Link](a);
  
            // printing the list
            [Link]("The list is: " + list);
Integer[] num = { 2, 4, 7, 5, 9 };
  
        // using [Link]() to find minimum element
        // using only 1 line.
        int min = [Link]([Link](num));
  
        // using [Link]() to find maximum element
        // using only 1 line.
        int max = [Link]([Link](num));

Hackerrank Time conversion


public static void main(String[] args) {

Scanner scan = new Scanner([Link]);


String time = [Link]();
String tArr[] = [Link](":");
String AmPm = tArr[2].substring(2,4);
int hh,mm,ss;
hh = [Link](tArr[0]);
mm = [Link](tArr[1]);
ss = [Link](tArr[2].substring(0,2));

String checkPM = "PM",checkAM ="AM";


int h = hh;
if([Link](checkAM) && hh==12)
h=0;
else if([Link](checkPM)&& hh<12)
h+=12;

[Link]("%02d:%02d:%02d",h,mm,ss);
}

// Modify array to make each 'i' contain the running sum


of prior elements
for (int i = 1; i < n; i++) {
sum[i] += sum[i - 1];
}
for (int i = m; i < n; i++) {
// If the sum of the piece is equal to 'd'
if (sum[i] - sum[i - m] == d) {
// Increment ways counter
numberOfWays++;
}
}
 >> right shift
class Test {
    public static void main(String args[])  {
       int x = -4;
       [Link](x>>1);   
       int y = 4;
       [Link](y>>1);   
    }    
}
Output:

-2
2

Sock Merchant HR
mport [Link].*;

class Solution {

public static void main(String[] args) {


Scanner scan = new Scanner([Link]);
int n = [Link]();
HashMap<Integer, Integer> colors = new HashMap<Integer, Integer>();

while(n-- > 0) {
int c = [Link]();
Integer frequency = [Link](c);

// If new color, add to map


if(frequency == null) {
[Link](c, 1);
}
else { // Increment frequency of existing color
[Link](c, frequency + 1);
}
}
[Link]();

// Count and print the number of pairs


int pairs = 0;
for(Integer frequency : [Link]()) {
pairs += frequency >> 1;
}
[Link](pairs);
}
}

Common questions

Powered by AI

In the Sock Merchant problem, the right shift operator (>>) is used to divide the frequency of each color's sock count by 2 to determine the number of pairs. This operator shifts the bits of the number to the right, effectively performing an integer division by two. Given that pairs are made up of two socks, the use of the right shift simplifies the calculation for determining complete pairs without needing modulo or division operations explicitly, thereby optimizing performance .

Modifying an array to contain the running sum of previous elements works by iterating over each position starting from the second (i.e., index 1), and updating the current element to be the sum of itself and the previous element. This accumulates a running total as each element captures the sum from the array start to its position. This approach is useful in scenarios like prefix sums, where quick queries computing the sum of any contiguous subarray are required. Such a structure allows for optimized query performance since each sum can be derived in constant time by simple subtraction .

The Java code snippet converts time from 12-hour format to 24-hour format by first splitting the input time into components of hours, minutes, and seconds using the split method. It checks the AM and PM designation by examining a substring of the seconds component. If the time is AM and the hour is 12, it resets the hour to 0 to represent midnight. Conversely, if the time is PM and the hour is less than 12, it adds 12 to the hour to accurately portray the time in the 24-hour format. The resulting time is formatted and printed using printf, ensuring the output is in 'hh:mm:ss' format with leading zeroes as necessary .

Using Collections.sort() on an ArrayList arranges the elements in ascending order based on their natural ordering or a specified comparator. Meanwhile, Collections.reverse() reverses the order of the elements in the list. Sorting followed by reversing can provide descending order sorting. The implications for performance depend on the size of the list, as both operations have a time complexity of O(n log n) for sorting and O(n) for reversing. Thus, for large lists, these operations can be computationally intensive, potentially affecting runtime performance .

Converting an ArrayList of objects to a primitive array type presents challenges primarily due to Java's type system, as ArrayLists store objects while arrays can store primitives. A direct conversion is complicated by the need to unbox each object to its primitive counterpart, requiring iteration and manual handling. Considerations include performance impacts due to unboxing, potential NullPointerExceptions if the list has any null elements, and ensuring any conversion correctly handles the expected array size and type. Additionally, care must be taken to avoid ClassCastException by correctly matching object types to corresponding primitive types during conversion .

The conversion of an array to a list using Arrays.asList() provides the advantage of efficient creation of a fixed-size list backed by the original array, allowing list operations without copying elements. It is also convenient for performing bulk operations on arrays that are typically easier with Lists. However, a significant disadvantage is that the resulting list cannot change in size as it is directly tied to the array's size, meaning that add() or remove() operations will throw UnsupportedOperationException, limiting its mutability .

To convert an ArrayList to an array in Java efficiently, you use a loop along with the get() method as demonstrated by assigning each element from the ArrayList to the corresponding array position. The code first initializes an array with the size of the ArrayList and then iterates through the list, retrieving each element using the get() method and storing it in the array at the current index. This method leverages the fact that ArrayLists allow indexed access to elements, making the conversion straightforward. The main benefit of using the get() method in this context is direct access to each element, ensuring efficient data transfer from the ArrayList to the array .

Scanner is often used in Java for parsing primitive types and strings from inputs, such as System.in, providing a simple, high-level abstraction for reading inputs. Compared to alternatives like BufferedReader, Scanner is intuitive for splitting inputs based on spaces or delimiters straightforwardly with methods like nextInt(). However, it is slower than BufferedReader due to its heavy parsing capability, which may impact performance in environments requiring large-scale input processing. BufferedReader, when used with StringTokenizer or other parsing methods, offers more nuanced control over input processing, often resulting in faster execution times due to reduced parsing overhead .

Using a HashMap in the Sock Merchant problem offers a performant approach to track the frequency of each sock color due to its average time complexity of O(1) for insertions and retrievals. The HashMap maps each color (as an Integer key) to its frequency (as an Integer value), allowing quick updates or retrievals of counts. This efficiency is crucial for handling potentially large input sizes typically present in real-world tasks, ensuring that the algorithm scales well with increased input. The ability to easily check and update existing entries streamlines the workflow for calculating total pairs .

The output of the right shift operation on negative integers in Java, such as applying >> to -4, results in shifting the bits to the right while preserving the sign bit (i.e., the leftmost bit) due to the use of arithmetic right shift. Therefore, -4 >> 1 yields -2, as the sign bit is retained and the number effectively halves while remaining negative. This behavior maintains the two's complement representation, ensuring that negative numbers still express their negative value correctly post-operation. The implications are particularly relevant in scenarios where bitwise manipulations on signed numbers could impact calculations and expected ranges .

You might also like