Create list with values 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.

Читайте также:  Java generic что такое

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.

Источник

Initialize ArrayList with values in Java

In this article, we will learn to initialize ArrayList with values in Java.
ArrayList is an implementation class of List interface in Java. It is used to store elements. It is based on a dynamic array concept that grows accordingly.
We can Initialize ArrayList with values in several ways. Let’s see some of them with examples.

Using Arrays.asList()

We can use Arrays.asList() method and pass it to ArrayList’s constructor to initialize ArrayList with values in java. This approach is useful when we already have data collection.

Initialize ArrayList with String values

When you pass Arrays.asList() to ArrayList constructor, you will get ArrayList object and you can modify the ArrayList the way you want.

💡 Did you know?

If you are using Array.asList() without ArrayList constructor to initialize list, then You can not structurally modify list after creating it.

Exception in thread “main” java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at Main.main(Main.java:13)

Although you can use list.set() method to change elements.

As you can see, 2nd element of the list changed from Mango to Banana

intialize ArrayList with Integer values

intialize ArrayList with float values

ArrayList < Integer >integerlist = new ArrayList < >( Arrays . asList ( 10.2f , 20.4f , 30.2f , 40.9f , 50.4f ) ) ;

Using Stream in Java 8

If you are working with Java 8 or higher version, then we can use of() method of Stream to initialize an ArrayList in Java. See the example below.

You can add or remove element from the list with this approach.

Using Factory Method in java 9

In Java 9, Java added some factory methods to List interface to create immutable list in Java. It can be used to initialize ArrayList with values in a single line statement.

💡 Did you know?

As the list is immutable, you can not add/remove new element and you can not use list’set() method to change elements.

Using double braces

Here is another approach to initialize ArrayList with values in Java, but it is not recommended because it creates an anonymous class internally that takes to verbose code and complexity.

That’s all about how to Initialize ArrayList with Values in Java.

Was this post helpful?

You may also like:

Update Value of Key in HashMap in Java

Create Array of Linked Lists in Java

Return ArrayList in Java

Create List with One Element in Java

How to Add Multiple Values for Single Key In HashMap in Java

[Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

Create ArrayList of Objects in Java

How to remove element from Arraylist in java while iterating

Share this

Author

Update Value of Key in HashMap in Java

Table of ContentsUsing the put() Method of HashMap Collection in JavaUsing the compute() Method of HashMap Collection in JavaUsing the merge() Method of the HashMap Collection in JavaUsing the computeIfPresent() Method of The HashMap Collection in JavaUsing the replace() Method of The HashMap Collection in JavaUsing the TObjectIntHashMap Class of Gnu.Trove Package in JavaUsing the […]

Create Array of Linked Lists in Java

Table of ContentsIntroductionLinked List in JavaApplication of Array of Linked ListsCreate Array of Linked Lists in JavaUsing Object[] array of Linked Lists in JavaUsing the Linked List array in JavaUsing the ArrayList of Linked Lists in JavaUsing the Apache Commons Collections Package Introduction In this article, we will look at how to Create an Array […]

Return ArrayList in Java

Table of ContentsReturn ArrayList in Java From a Static MethodReturn ArrayList in Java From a Non-static MethodConclusion This article discusses cases of returning an ArrayList in Java from a method. An ArrayList in Java is a collection of elements of the same data type under a single variable name. In different cases, you can return […]

Create List with One Element in Java

Table of ContentsUsing Collections.singletonList()Using Array.asList() method [ Immuatable list]Using new ArrayList with Array.asList() method [ Mutable list] In this post, we will see how to create List with One Element in java.. Using Collections.singletonList() This is best way to create List with single element if you need an immutable List. [crayon-64b6d95fe0e84268737316/] Output [crayon-64b6d95fe0e89260110255/] If you […]

How to Add Multiple Values for Single Key In HashMap in Java

Table of ContentsHashMapCan HashMap Store Multiple Values AutomaticallyWays to Add Multiple Values for Single Key In HashMap in JavaUsing the Standard LibraryUsing Apache Commons LibraryUsing Google Guava LibraryUsing TreeSet as ValuesUsing a Wrapper ClassUsing Java TuplesUsing compute() Function in JDK 8Conclusion This article discusses the HashMap in Java and how to add multiple values for […]

java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

[Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

Table of ContentsReason for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListFixes for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListUse ArrayList’s constructorAssign Arrays.asList() to List reference rather than ArrayList In this post, we will see how to fix java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList. ClassCastException is runtime exception which indicate that code has tried to […]

Источник

How to declare ArrayList with values in Java? Examples

Sometimes you want to create an ArrayList with values, just like you initialize t at the time of declaration, as shown below:

but unfortunately, ArrayList doesn’t support such kind of declaration in Java. But don’t worry, there is a workaround to declare an ArrayList with values e.g. String, integers, floats, or doubles by using the Arrays.asList() method, which is nothing but a shortcut to convert an Array to ArrayList.

Declaring ArrayList with values in Java

Here is a code example to show you how to initialize ArrayList at the time of declaration:

ArrayList numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6));

This is how you declare an ArrayList of Integer values. You can do the same to create an ArrayList with String objects as well, e.g.

ArrayList cities = new ArrayList<>( Arrays.asList("London", "Tokyo", "New York"));

Similarly here is how you should create ArrayList with float values:

ArrayList floats = new ArrayList<>(Arrays.asList(3.14f, 6.28f, 9.56f));

don’t forget the suffix ‘f’, it’s important because by default floating-point numbers are double in Java.

Some programmer’s also like to declare a List with values in one line as:

List listOfInts = Arrays.asList(1, 2, 3);

This is Ok to print values, but it’s not an ArrayList. You cannot add or remove elements into this list but when you create an ArrayList like new ArrayList(Arrays.asList()) , you get a regular ArrayList object, which allows you to add, remove and set values.

Here is a nice summary of code examples of how to make an ArrayList of values in Java:

How to declare ArrayList with values in Java

That’s all about how to declare an ArrayList with values in Java. You can use this technique to declare an ArrayList of integers, String, or any other object. It’s truly useful for testing and demo purpose, but I have also used this to create an ArrayList of an initial set of fixed values.

  • What is the difference between an array and an ArrayList in Java? (answer)
  • Difference between LinkedList and ArrayList in Java? (answer)
  • How to remove elements from ArrayList in Java? (example)
  • What is the difference between HashSet and ArrayList in Java? (answer)
  • How to reverse an ArrayList in Java? (solution)
  • What is the difference between ArrayList and HashMap in Java? (answer)
  • How to loop over ArrayList in Java? (answer)
  • How to sort an ArrayList? (solution)
  • How to get the subList() from an ArrayList in Java? (solution)
  • The difference between the length and size of ArrayList? (answer)
  • How to sort the ArrayList in decreasing order? (example)
  • Difference between CopyOnWriteArrayList and synchronized ArrayList in Java? (answer)
  • What is the difference between ArrayList and Vector in Java? (answer)
  • How to avoid ConcurrentModificationException while looping over ArrayList? (solution)

Further Reading
If you a beginner in Java and just started learning, then you can read Head First Java 2nd Edition, but if you are an experienced Java developer and looking forward to taking your knowledge of Java Collections framework to next level then read Java Generics and Collections from Maurice Naftalin.

Источник

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