Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Jack Pritom Soren
Jack Pritom Soren

Posted on

     

ArrayList (Java Collections)

Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but there is no size limit. We can add or remove elements anytime. So, it is much more flexible than the traditional array. It is found in the java.util package. It is like the Vector in C++. The ArrayList in Java can have the duplicate elements also. It implements the List interface so we can use all the methods of the List interface here. The ArrayList maintains the insertion order internally.

Java ArrayList Example :

Example 1 :

import java.util.*;public class Array_List {    public static void main(String[] args) {        ArrayList<String> list = new ArrayList<String>(); // Creating arrayList        list.add("James"); // adding object in arrayList        list.add("John");        for (int i = 0; i < list.size(); i++) {            System.out.println(list.get(i)); // printing arrayList        }    }}//OutPut:  James  John
Enter fullscreen modeExit fullscreen mode

Example 2:

import java.util.*;public class Array_List {    public static void main(String[] args) {        ArrayList<String> list = new ArrayList<String>(); // Creating arrayList        Scanner scanner = new Scanner(System.in);        System.out.println("Enter the Lenght: ");        int number = scanner.nextInt();        scanner.nextLine();        for (int i = 1; i <= number; i++) {            list.add(scanner.nextLine());        }        System.out.println(list);    }}
Enter fullscreen modeExit fullscreen mode

We can not create an array list of the primitive types, such as int, float, char, etc. It is required to use the required wrapper class in such cases. For example:

ArrayList<int> al = ArrayList<int>(); // does not work  ArrayList<Integer> al = new ArrayList<Integer>(); // works fine
Enter fullscreen modeExit fullscreen mode

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Software Engineer (SWE) | Frontend | JavaScript | React | Next JS | Angular JS
  • Location
    Bangladesh
  • Education
    B.Sc in Computer Science & Engineering
  • Work
    SQUARE Health Ltd.
  • Joined

More fromJack Pritom Soren

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp