add a key value pair in java arraylist

arraylist in java मै हम देखगे क्या होता है arraylist क्या होता कैसे use करते है 

An ArrayList is a dynamic, resizable array-like data structure that can hold elements of the same data type.

add a key value pair in arraylist in java


Q . what is arraylist

An ArrayList is a fundamental data structure in programming that provides a dynamic, resizable array-like container to store elements of the same data type. It is a core component in many programming languages and libraries, serving as a powerful tool for managing collections of data in various applications.

advantage of arraylist

Dynamic Size  -  ArrayLists can grow or shrink dynamically, allowing for easy addition or removal of elements without manually managing the size.

 

Indexed Access  -  Elements in an ArrayList can be accessed using an index, providing fast and efficient retrieval of elements.

 

Homogeneous Elements  - ArrayLists hold elements of the same data type, ensuring type safety and consistency

 

Standard Library Support - Many programming languages include ArrayList implementations in their standard libraries, making them readily available for use without additional setup

 

Versatility  - ArrayLists can be used in various scenarios, such as managing lists of objects, implementing dynamic arrays, or building stacks and queues.

 

Iteration and Enumeration -  ArrayLists support easy iteration and enumeration through their elements using loops or iterators.

Disadvantage of arraylist

Dynamic Resizing Overhead - The dynamic resizing process of an ArrayList may incur performance overhead when the list grows large, as the underlying array needs to be expanded and elements copied to a new memory location

Inefficient Insertions/Deletions - Frequent insertions or deletions at arbitrary positions in an ArrayList can be inefficient as it may require shifting elements to maintain contiguous memory


I add a key value pair in ArrayList in Java using Map.Entry class:


import java.util.ArrayList;

import java.util.Map;

import java.util.AbstractMap.SimpleEntry;

 

public class Main 

{

    public static void main(String[] args)

 {

        ArrayList<Map.Entry<String, Integer>> keyValuePairs = new ArrayList<>();

 

// Adding key-value pairs to the ArrayList

        keyValuePairs.add(new SimpleEntry<>("key1", 10));

        keyValuePairs.add(new SimpleEntry<>("key2", 20));

        keyValuePairs.add(new SimpleEntry<>("key3", 30));

 

        // Accessing key-value pairs from the ArrayList

        for (Map.Entry<String, Integer> entry : keyValuePairs)

 {

            String key = entry.getKey();

            Integer value = entry.getValue();

            System.out.println("Key: " + key + ", Value: " + value);

        }

    }

}

और भी पढ़े click करे  👇

print jumping all numbers in java






एक टिप्पणी भेजें

0 टिप्पणियाँ