List with arraylist in java

Class ArrayList

Type Parameters: E — the type of elements in this list All Implemented Interfaces: Serializable , Cloneable , Iterable , Collection , List , RandomAccess Direct Known Subclasses: AttributeList , RoleList , RoleUnresolvedList

Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null . In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector , except that it is unsynchronized.)

The size , isEmpty , get , set , iterator , and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.

Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.

Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be «wrapped» using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list:

List list = Collections.synchronizedList(new ArrayList(. ));

The iterators returned by this class’s iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException . Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

This class is a member of the Java Collections Framework.

Читайте также:  Абсолютное позиционирование

Источник

Java List – Example Lists in Java

Ihechikara Vincent Abba

Ihechikara Vincent Abba

Java List – Example Lists in Java

You can use the Java List interface to store objects/elements in an ordered collection. It extends the Collection interface.

The List interface provides us with various methods for inserting, accessing, and deleting elements in a collection.

In this article, you’ll learn how to extend and implement the List interface in Java, and how to interact with elements in a collection.

Implementation Classes of the Java List Interface

Here are the different implementation classes of the List interface in Java:

  • AbstractList.
  • AbstractSequentialList.
  • ArrayList.
  • AttributeList.
  • CopyOnWriteArrayList.
  • LinkedList.
  • RoleList.
  • RoleUnresolvedList.
  • Stack.
  • Vector.

The most commonly used implementation of the List interface are ArrayList and LinkedList .

Since both classes above implement the List interface, they make use of the same methods to add, access, update, and remove elements in a collection.

In this tutorial, we’ll have a look at how we can add, access, update, and remove elements in a collection using the ArrayList .

How to Implement a List in Java Using ArrayList

Unlike arrays in Java, which have a specified size, the ArrayList is more dynamic when it comes to storing elements. This means that you can add items as you please.

Here’s how you can create an ArrayList :

import java.util.ArrayList; public class Main < public static void main(String[] args) < ArrayListstudents = new ArrayList(); > >

In the code above, we first imported the ArrayList class: import java.util.ArrayList; .

We then created a new ArrayList object called students : ArrayList students = new ArrayList(); .

Note that the data types of elements that would be stored in the ArrayList were specified in angle brackets: .

How to Add Elements to the ArrayList

You can use the add() method to add elements to the ArrayList .

import java.util.ArrayList; public class Main < public static void main(String[] args) < ArrayListstudents = new ArrayList(); students.add("John"); students.add("Jane"); students.add("Doe"); System.out.println(students); // [John, Jane, Doe] > >

In the code above, we passed the element to be added to the ArrayList as a parameter: students.add(«Doe») .

How to Access Elements in the ArrayList

To access elements in the ArrayList , you make use of the get() method. Here’s how:

import java.util.ArrayList; public class Main < public static void main(String[] args) < ArrayListstudents = new ArrayList(); students.add("John"); students.add("Jane"); students.add("Doe"); System.out.println(students.get(1)); // Jane > > 

As can be seen above, we passed in the index of the element to be accessed as a parameter to the get() method: students.get(1) .

Читайте также:  overflow

How to Update Elements in the ArrayList

To update the value of elements in the ArrayList , you make use of the set() method.

It takes two parameters: the index of the element to be updated, and the new value.

import java.util.ArrayList; public class Main < public static void main(String[] args) < ArrayListstudents = new ArrayList(); students.add("John"); students.add("Jane"); students.add("Doe"); students.set(2,"Jade"); System.out.println(students); // [John, Jane, Jade] > >

How to Remove Elements in the ArrayList

To remove elements in the ArrayList , you make use of the remove() method. We also use the index to specify which element to remove.

import java.util.ArrayList; public class Main < public static void main(String[] args) < ArrayListstudents = new ArrayList(); students.add("John"); students.add("Jane"); students.add("Doe"); students.remove(2); System.out.println(students); // [John, Jane] > > 

You can use the clear() method to remove all the elements in the collection:

import java.util.ArrayList; public class Main < public static void main(String[] args) < ArrayListstudents = new ArrayList(); students.add("John"); students.add("Jane"); students.add("Doe"); students.clear(); System.out.println(students); // [] > > 

Although the ArrayList and LinkedList classes both have the same methods as seen in the examples in this article, the LinkedList class has some additional methods like:

  • addFirst() adds an element at the beginning of the list.
  • addLast() adds an element at the end of the list.
  • getFirst() returns the first element of the list.
  • getLast() returns the last element of the list.
  • removeFirst() removes the first element of the list.
  • removeLast() removes the last element of the list.

Summary

In this article, we talked about the List interface in Java. You use it to store ordered collections of elements.

We had a look at some of the implementation classes of the List interface. The most commonly used are the ArrayList and LinkedList classes.

Using code examples, we saw how to add, access, update, and remove elements in a collection with the ArrayList .

Although both ArrayList and LinkedList have similar methods, we highlighted some of the additional methods that you can use with the LinkedList class.

Источник

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.

Читайте также:  Python pil imagedraw line

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:

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); >> > 

Источник

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