Java arraylist example with objects

Java ArrayList

The ArrayList class is a resizable array, which can be found in the java.util package.

The difference between a built-in array and an ArrayList in Java, is that the size of an array cannot be modified (if you want to add or remove elements to/from an array, you have to create a new one). While elements can be added and removed from an ArrayList whenever you want. The syntax is also slightly different:

Example

Create an ArrayList object called cars that will store strings:

import java.util.ArrayList; // import the ArrayList class ArrayList cars = new ArrayList(); // Create an ArrayList object 

If you don’t know what a package is, read our Java Packages Tutorial.

Add Items

The ArrayList class has many useful methods. For example, to add elements to the ArrayList , use the add() method:

Example

import java.util.ArrayList; public class Main < public static void main(String[] args) < ArrayListcars = new ArrayList(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); System.out.println(cars); > > 

Access an Item

To access an element in the ArrayList , use the get() method and refer to the index number:

Example

Remember: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

Change an Item

To modify an element, use the set() method and refer to the index number:

Example

Remove an Item

To remove an element, use the remove() method and refer to the index number:

Example

To remove all the elements in the ArrayList , use the clear() method:

Example

ArrayList Size

To find out how many elements an ArrayList have, use the size method:

Example

Loop Through an ArrayList

Loop through the elements of an ArrayList with a for loop, and use the size() method to specify how many times the loop should run:

Example

public class Main < public static void main(String[] args) < ArrayListcars = new ArrayList(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); for (int i = 0; i < cars.size(); i++) < System.out.println(cars.get(i)); >> > 

You can also loop through an ArrayList with the for-each loop:

Example

public class Main < public static void main(String[] args) < ArrayListcars = new ArrayList(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); for (String i : cars) < System.out.println(i); >> > 

Other Types

Elements in an ArrayList are actually objects. In the examples above, we created elements (objects) of type «String». Remember that a String in Java is an object (not a primitive type). To use other types, such as int, you must specify an equivalent wrapper class: Integer . For other primitive types, use: Boolean for boolean, Character for char, Double for double, etc:

Читайте также:  Return data type php

Example

Create an ArrayList to store numbers (add elements of type Integer ):

import java.util.ArrayList; public class Main < public static void main(String[] args) < ArrayListmyNumbers = new ArrayList(); myNumbers.add(10); myNumbers.add(15); myNumbers.add(20); myNumbers.add(25); for (int i : myNumbers) < System.out.println(i); >> > 

Sort an ArrayList

Another useful class in the java.util package is the Collections class, which include the sort() method for sorting lists alphabetically or numerically:

Example

Sort an ArrayList of Strings:

import java.util.ArrayList; import java.util.Collections; // Import the Collections class public class Main < public static void main(String[] args) < ArrayListcars = new ArrayList(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); Collections.sort(cars); // Sort cars for (String i : cars) < System.out.println(i); >> > 

Example

Sort an ArrayList of Integers:

import java.util.ArrayList; import java.util.Collections; // Import the Collections class public class Main < public static void main(String[] args) < ArrayListmyNumbers = new ArrayList(); myNumbers.add(33); myNumbers.add(15); myNumbers.add(20); myNumbers.add(34); myNumbers.add(8); myNumbers.add(12); Collections.sort(myNumbers); // Sort myNumbers for (int i : myNumbers) < System.out.println(i); >> > 

Источник

Java ArrayList class

An ArrayList in Java represents a resizable list of objects. We can add, remove, find, sort and replace elements in this list.

ArrayList is part of the collections framework. It extends AbstractList which implements List interface. The List extends Collection and Iterable interfaces in hierarchical order.

ArrayList Hierarchy

ArrayList has the following features –

  1. Ordered – Elements in ArrayList preserve their ordering which is by default the order in which these were added to the list.
  2. Index-based – Elements can be randomly accessed using index positions. Index starts with ‘0’ .
  3. Dynamic resizing – ArrayList grows dynamically when more elements need to be added than its current size.
  4. Non-synchronized – ArrayList is not synchronized by default. The programmer needs to use the synchronized keyword appropriately or simply use the Vector class.
  5. Duplicates allowed – We can add duplicate elements in ArrayList. It is not possible in sets.

2. How does ArrayList Works?

ArrayList class is implemented with a backing array. The elements added or removed from ArrayList are actually modified in the backing array. All ArrayList methods access this backing array and get/set elements in the same array.

Читайте также:  Использование ui файла python

ArrayList can be seen as resizable-array implementation in Java.

public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable, java.io.Serializable < transient Object[] elementData; //backing array private int size; //array or list size //more code >

3. Java Array vs. ArrayList

An array is a fixed-size data structure where the size has to be declared during initialization. Once the size of an array is declared, it is impossible to resize the array without creating a new one.

Integer[] numArray = new Integer[5];

The ArrayList offers to remove this sizing limitation. An ArrayList can be created with any initial size (default 16), and when we add more items, the size of the ArrayList grows dynamically without any intervention by the programmer.

ArrayList numList = new ArrayList<>();

Many people refer to ArrayList as dynamic array.

4.1. How to create an ArrayList

To create ArrayList , we can call one of its constructors.

Constructor Description
ArrayList() It is the default constructor. It creates an empty ArrayList with an initial capacity of 16.
ArrayList(int capacity) It creates an empty ArrayList with the given initial capacity .
ArrayList(Collection c) It creates an ArrayList that is initialized with the elements of the collection c .

Given below program shows how to declare and initialize an ArrayList in Java.

ArrayList list = new ArrayList(); List numbers = new ArrayList<>(6); Collection setOfElements = . ; List numbers = new ArrayList<>(setOfElements); 

A generic ArrayList clearly mentions the type of objects it will store. It helps in avoiding a lot of defects caused by incorrect typecasting.

//Non-generic arraylist - NOT RECOMMENDED !! ArrayList list = new ArrayList(); //Generic Arraylist with default capacity List numbers = new ArrayList<>(); //Generic Arraylist with the given capacity List numbers = new ArrayList<>(6); //Generic Arraylist initialized with another collection List numbers = new ArrayList<>( Arrays.asList(1,2,3,4,5) ); 

4.3. ArrayList of primitive types

In ArrayList, we are supposed to add only objects. But in case we are required to add primitive data types such as int , float etc, we can use their wrapper classes for providing type information during ArrayList initialization.

When we add the int or float value to ArrayList, values are automatically upcasted.

In given an example, we have created an array list of Integer values. When we add int value 1 , it is automatically converted to new Integer(1) .

List numbers = new ArrayList<>(6); numbers.add(1); // This runs fine

4.4. Create and initialize ArrayList in single line

Читайте также:  Блок с тенью

Generally, creating an arraylist is a multi-step process. In first step, we create an empty array list. In later steps, we populate the list with elements – one by one.

Using Arrays.asList() and constructor ArrayList(collection) , we can combine these steps in a single statement.

ArrayList charList = new ArrayList<>(Arrays.asList(("A", "B", "C"));

5. Get element from ArrayList

To get an element from the ArrayList , we have two ways.

If we know the index location in advance, then we can call the get(index) which returns the element present at index location.

Please remember that indexes start with zero.

ArrayList alphabetsList = new ArrayList<>(Arrays.asList(("A", "B", "C")); String aChar = alphabetsList.get(0); // A

Use iterator() or listIterator() to get the reference of Iterator instance. We can use this iterator to iterate the elements in the ArrayList.

The next() method returns the element at the current index location and increments the index count by one. Call hasNext() method to check if there are more elements in the list to iterate.

ArrayList digits = new ArrayList<>(Arrays.asList(1,2,3,4,5,6)); Iterator iterator = digits.iterator(); while(iterator.hasNext())

6. Iterating over an ArrayList

Java example of iterating over an ArrayList using the Iterator.

ArrayList digits = new ArrayList<>(Arrays.asList(1,2,3,4,5,6)); Iterator iterator = digits.iterator(); while(iterator.hasNext())

Java example of iterating over an ArrayList using for loop. When using for loop, we need to get the current element using the current index counter.

ArrayList digits = new ArrayList<>(Arrays.asList(1,2,3,4,5,6)); for(int i = 0; i

forEach loop works pretty much the same as simple for loop. The only difference is that the JVM manages the counter initialization and increment. We get the next element in each iteration in the loop.

ArrayList digits = new ArrayList<>(Arrays.asList(1,2,3,4,5,6)); for(Integer d : digits)

7. Finding the length of the ArrayList

To get the size of the ArrayList, we use the size() method.

ArrayList digits = new ArrayList<>(Arrays.asList(1,2,3,4,5,6)); System.out.print( digits.size() ); // 6

ArrayList sort() method sorts the list according to the order induced by the specified Comparator instance. All elements in the list must be mutually Comparable .

public class AgeSorter implements Comparator  < @Override public int compare(Employee e1, Employee e2) < //comparison logic >>
ArrayList employees = new ArrayList<>(); employees.add(new Employee(. )); employees.add(new Employee(. )); employees.add(new Employee(. )); employees.sort(new NameSorter());

In this Java tutorial, we learned to work with ArrayList in Java. We learned to create, modify and perform advanced operations in the ArrayList class.

Источник

Оцените статью