Java add null object to arraylist

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.

Читайте также:  Css for position center

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.

Источник

ArrayList add() method in Java

add() method is used to add the elements into the ArrayList. There are two overloaded implementations of the add method for the ArrayList class .

Let’s look at the overloaded methods one by one

public boolean add(E e)

  • Method declaration – public boolean add(E e)
  • What does it do? – It appends the element passed in the argument to the end of the ArrayList
  • What does it return? – It returns true on successful insertion of the element. Otherwise, it will return false.

Now, we will take a list of strings and try to add the elements to it using the add() function.

public class Codekru < public static void main(String[] args) < ArrayListal = new ArrayList(); // appending the elements at the end of the list al.add("first"); al.add("second"); al.add("third"); // printing the contents of the list System.out.println("ArrayList contents: " + al.toString()); > >
ArrayList contents: [first, second, third]
Time complexity of ArrayList add() method

ArrayList internally uses an array to store the data, and the array size becomes the capacity of the ArrayList. Keeping that in mind

  • The best case time complexity of the ArrayList add() method is O(1). It’s when the ArrayList’s capacity is not full and more elements can be added without increasing its capacity.
  • The worst-case time complexity of the ArrayList add() method is O(n). It’s when the ArrayList’s capacity became equal to its size, and now the array size has to be increased to accommodate new elements. So, it uses Arrays.copyOf() to copy the old array into a new one with the updated capacity. This operation takes O(n) time, and thus overall complexity of the add() method becomes O(n).
What if we use the method on a null ArrayList?

Here, we will get a NullPointerException as illustrated by the below program.

public class Codekru < public static void main(String[] args) < ArrayListal = new ArrayList(); al = null; // appending the elements at the end of the list al.add("first"); // printing the contents of the list System.out.println("ArrayList contents: " + al.toString()); > >
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.ArrayList.add(Object)" because "al" is null
What if we try to add the null object into an ArrayList?

ArrayList inserts the null object like any other object.

public class Codekru < public static void main(String[] args) < ArrayListal = new ArrayList(); // appending the elements at the end of the list al.add(null); al.add("first"); // printing the contents of the list System.out.println("ArrayList contents: " + al.toString()); > >
ArrayList contents: [null, first]

public void add(int index, E element)

  • Method declaration – public void add(int index, E element)
  • What does it do? – It inserts the element passed in the argument at the specified index into the ArrayList. Remember, the indexing here starts from 0, so if you want to add the element at the 3rd position, you must pass the index as 2 into the function.
  • What does it return? – It does not return anything as the function’s return type is void.
Code example
public class Codekru < public static void main(String[] args) < ArrayListal = new ArrayList(); // appending the elements at the end of the list al.add("First"); al.add("Third"); // inserting the element at 2nd postion, by passing index as 1 al.add(1, "Second"); // printing the contents of the list System.out.println("ArrayList contents: " + al.toString()); > >
ArrayList contents: [First, Second, Third]
Time complexity of ArrayList add(int index, E element) method

The time complexity of the ArrayList add(int index, E element) method is O(n).

What if we put the index greater than ArrayList size?

Here, we will get the IndexOutOfBoundsException as illustrated by the below program.

public class Codekru < public static void main(String[] args) < ArrayListal = new ArrayList(); // appending the elements at the end of the list al.add("First"); al.add("Third"); // putting index as 3, which is greater than list's size (2) al.add(3, "Second"); // printing the contents of the list System.out.println("ArrayList contents: " + al.toString()); > >
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 2 at java.base/java.util.ArrayList.rangeCheckForAdd(ArrayList.java:756) at java.base/java.util.ArrayList.add(ArrayList.java:481)

Please visit this link to learn more about the ArrayList class of java and its other functions or methods.

We hope that you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at [email protected].

Источник

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.

Источник

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