Java arraylist массивов int

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.

Читайте также:  Шаблонизатор html кода pug

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.

Источник

How to convert int array to ArrayList of Integer in Java 8? [Example/Tutorial]

I once asked this question to one of the Java developers during an Interview and like many others, he answered that Arrays.asList() can convert an array of primitive integer values to ArrayList in Java, which was actually wrong. Even though, Arrays.asList() is the go-to method to convert an Array to ArrayList in Java when it comes to converting a primitive array to ArrayList , this method is not useful. The Arrays.asList() method does not deal with boxing and it will just create a List which is not what you want. In fact, there was no shortcut to convert an int[] to ArrayList or long[] to ArrayList till Java 8.

From JDK 8 onwards, you either had to make a utility method or need to use general-purpose Java libraries like Google Guava or Apache Commons to convert an array of primitive values. byte, short, char, int, long, float, and double to ArrayList of Byte, Character, Short, Integer, Long, Float, and Double wrapper classes.

Though from Java 8 onwards, you can use the java.util.Stream to convert an int[] to ArrayList . There are specialized stream implementations for primitive data types like IntStream for primitive int, LongStream for primitive long, and DoubleStream for primitive double, which can convert an array of primitive values to a stream of primitive values.

Once you get the Stream of int values, you can use the boxed() method to convert it to Stream of Integer wrapper objects. After that you can just convert Stream to List as shown in that article i.e. you can use the collect() method of the stream with Collectors.toList() to get a list.

int[] to List

If you want ArrayList instead of List then you can pass a Supplier to Collectors, which will accumulate elements into an ArrayList as shown below:

int[] primes = new int[]2, 3, 5, 7, 11, 13, 17>; ArrayListInteger> list = IntStream.of(primes) .boxed() .collect(Collectors.toCollection(ArrayList::new));

Alternatively, you can also use the copy constructor of the Collection interface to create an ArrayList by copying all elements from the List instance as shown in the following example:

ListInteger> list = IntStream.of(primes) .boxed() .collect(Collectors.toList()); ArrayListInteger> arraylist = new ArrayList<>(list);

What is this code doing? Well, if you are not very familiar with Java 8, Stream, and method reference then here is a step by step explanation of the above one-liner of converting a primitive array to ArrayList in JDK 8:

1) The IntStream.of(primes) is converting an int array to an IntStream object.

2) The boxed() method of IntStream convert applies boxing on each element of IntStream and returns a Stream of Integer i.e it converts IntStream to Stream object.

3) The collect() method collects all elements of Stream into any Collection class by using Collectors of Java 8. A Collector encapsulates the functions used as arguments to collect(Supplier, BiConsumer, BiConsumer) , allowing for reuse of collection strategies and composition of collect operations such as multiple-level grouping or partitioning.

4) The Collectors.toCollection() method collects elements of Stream into a Collection which is specified by the first parameter. Here we are passing ArrayList::new which is a constructor reference, which means all elements of Stream will be collected into an ArrayList. See The Complete Java MasterClass to learn more.

How to convert int[] to ArrayList of Integer in Java 8

By far, That was the simplest way to convert an array of primitive data types to a List of wrapper objects like an array of ints to ArrayList of Integers.

Btw, there is another way to convert a primitive array to ArrayList in Java 8 by using the Arrays.stream() method, which converts an array to Stream in Java 8.

This method is equivalent to IntStream.of(int[]) and return an IntStream. The rest of the code will remain the same i.e. you can use the following one-liner to convert an int[] to ArrayList in JDK 8:

ArrayListInteger> list = Arrays.stream(ints) .boxed() .collect(Collectors.toCollection(ArrayList::new));

Java Program to convert int Array to ArrayList of Integer in Java

Here is the full Java program to convert an int[] to ArrayList in Java 8:

import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; /* * Java Program to convert a long[] to ArrayList in JDK 8 */ public class Main < public static void main(String[] args) throws Exception < // converting an array of Integer to ArrayList of Integer int[] primes = new int[]2, 3, 5, 7, 11, 13, 17>; System.out.println("primitive int array: " + Arrays.toString(primes)); ArrayList listOfInts = IntStream.of(primes) .boxed() .collect(Collectors.toCollection(ArrayList::new)); System.out.println("ArrayList : " + listOfInts); long[] numbers = new long[]202, 3003, 2002, 3003, 222>; ArrayListLong> listOfLong = Arrays.stream(numbers) .boxed() .collect(Collectors.toCollection(ArrayList::new)); System.out.println("primitive long array: " + Arrays.toString(numbers)); System.out.println("ArrayList : " + listOfLong); > > Output: primitive int array: [2, 3, 5, 7, 11, 13, 17] ArrayList : [2, 3, 5, 7, 11, 13, 17] primitive long array: [202, 3003, 2002, 3003, 222] ArrayListLong> : [202, 3003, 2002, 3003, 222]

From the output, it’s clear that both ways of converting an array of primitive values to ArrayList of objects work fine. You can use whatever you want. See From Collections to Streams in Java 8 Using Lambda Expressions to learn more.

How to convert int[] to ArrayList of Integer in Java 6,7

If you are not running in Java 8 and want to convert int[] to ArrayList<> on an earlier version of Java, like JDK 6 and JDK 7, then you have two choices, either use Google’s Guava or Apache commons library as shown here or write your own conversion method as shown below:

/* * Java Program to convert int[] to ArrayList */ public class Main < public static void main(String[] args) throws Exception < int[] primes = new int[]2, 3, 5, 7, 11, 13, 17>; System.out.println("primitive int array: " + Arrays.toString(primes)); ArrayList listOfInts = new ArrayList<>(primes.length); for(int i: primes) < listOfInts.add(i); >System.out.println("ArrayList : " + listOfInts); > > Output primitive int array: [2, 3, 5, 7, 11, 13, 17] ArrayList : [2, 3, 5, 7, 11, 13, 17]

The code is pretty simple and self-explanatory. We are iterating over ArrayList using enhanced for loop of Java 5 and adding each int value from array to ArrayList. When you add, Java uses autoboxing to convert an int value to an Integer object, so in the end, you have an ArrayList of Integer. Though, you can also use other ways to loop over an array, like by using for or while loop.

One slightly important thing to note is initializing ArrayList with the length of the array. This prevents ArrayList from being resizing multiple times.

If you remember, by default ArrayList initializes with 10 elements and then keeps resize when it is about to fill, I guess when the load factor grows up to 0.75 it resizes and doubles itself. This involves a lot of array copy, which can slow down your application.

It’s also a Java collection best practice to provide size while creating an instance of any Collection class like ArrayList . See these Java Performance courses for more such tips.

That’s all about how to convert an int[] to ArrayList in Java. You can use this technique to convert any primitive array to ArrayList of respective wrapper class like you can convert a long[] to ArrayList , a float[] to ArrayList , a double[] to ArrayList , a char[] to ArrayList , a short[] to ArrayList , and a byte[] to ArrayList in Java.

  • How to join String in Java 8 (example)
  • How to use forEach() method in Java 8 (example)
  • How to use filter() method in Java 8 (tutorial)
  • 5 Books to Learn Java 8 from Scratch (books)
  • Java 8 — Stream.collect() Example (example)
  • How to use Stream class in Java 8 (tutorial)
  • What is the double-colon operator of Java 8? (tutorial)
  • How to join String in Java 8 (example)
  • 20 Examples of Date and Time in Java 8 (tutorial)
  • 10 Free Courses for Experienced Java Programmers (courses)
  • How to use peek() method in Java 8 (example)
  • Java 8 Stream.findFirst() + filter() example (see)
  • How to sort the may by values in Java 8? (example)
  • How to convert List to Map in Java 8 (solution)
  • Difference between abstract class and interface in Java 8? (answer)
  • How to use peek() method in Java 8 (example)
  • How to format/parse the date with LocalDateTime in Java 8? (tutorial)
  • 5 Free Courses to learn Java 8 and 9 (courses)

Thanks a lot for reading this article so far. If you like this article then please share it with your friends and colleagues. If you have any questions or feedback then please drop a comment.

P. S. — In general, you should use Stream if you are using Java 8, it’s cleaner than the Java 6 approach and also takes just one line to convert a primitive array to ArrayList. If you don’t know much about Stream and Java 8, I suggest you read a good book on Java 8 to learn more about IntStream and other Stream features like Java 8 in Action.

Источник

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