• Latest Code...

    Featured Post

    Implementing Hilt in a Kotlin Android Jetpack Compose Project with MVVM Architecture

     In modern Android development, maintaining a scalable codebase can be challenging, especially when it comes to dependency management. Hilt,...

    Declare an array, Converting an array to list and create ArrayList (ArrayList) from array (T[]) in Java



    Declare an Array in Java

    You can either use array declaration or array literal (but only when you declare and affect the variable right away, array literals cannot be used for re-assigning an array).

    For primitive types:

    int[] myIntArray = new int[3];
    int[] myIntArray = {1,2,3};
    int[] myIntArray = new int[]{1,2,3};

    For classes, for example String, it's the same:

    String[] myStringArray = new String[3];
    String[] myStringArray = {"a","b","c"};
    String[] myStringArray = new String[]{"a","b","c"};


    Converting an array to list in Java

    Integer[] spam = new Integer[] { 1, 2, 3 };
    Arrays.asList(spam);

    Or

    ArrayList<String> stock_list = new ArrayList<String>();
    stock_list.add("stock1");
    stock_list.add("stock2");
    String[] stockArr = new String[stock_list.size()];
    stockArr = stock_list.toArray(stockArr);
    for(String s : stockArr)
    System.out.println(s);


    and
    Create ArrayList (ArrayList<T>) from array (T[]) in Java

    new ArrayList<Element>(Arrays.asList(array))

    Or

    Element[] array = new Element[] { new Element(1),new Element(2),new Element(3) };

    The simplest answer is to do:

    List<Element> list = Arrays.asList(array);


    Happy Coding!!!


    Contact Form

    Name

    Email *

    Message *