- Java list of primitive data types in java
- Which Data Type Cannot be Stored in Java ArrayList?
- List of Primitive Integer Values in Java
- 1. Overview
- 2. Autoboxing
- 3. Using the Stream API
- 4. Using Trove
- 5. Using Fastutil
- 6. Using Colt
- 7. Using Guava
- 8. Conclusion
- Why an ArrayList in Java cannot contain primitives like int , double or char
- What’s the solution?
- Why does this happen?
Java list of primitive data types in java
The barrier against this is that there would be an explosion of such classes, as you’d multiply the number of primitive types by the number of collection types. To solve this more neatly in the language, you’d need generics to allow primitive types to serve as type parameters, and improve the interaction between arrays and generics.
Which Data Type Cannot be Stored in Java ArrayList?
The ArrayList class implements a growable array of objects. ArrayList cannot hold primitive data types such as int, double, char, and long. With the introduction to wrapped class in java that was created to hold primitive data values. Objects of these types hold one value of their corresponding primitive type(int, double, short, byte). They are used when there is a usage of the primitive data types in java structures that require objects such as JLists, ArrayLists. Now, in order to hold primitive data such as int and char in ArrayList are explained.
Primitive data types cannot be stored in ArrayList but can be in Array . ArrayList is a kind of List and List implements Collection interface. The Collection container expects only Objects data types and all the operations done in Collections, like iterations, can be performed only on Objects and not Primitive data types. An ArrayList cannot store ints. To place ints in ArrayList, we must convert them to Integers. This can be done in the add() method on ArrayList. Each int must be added individually.
Case 1: Integers in ArrayList
To place int in ArrayList, First, they are converted into Integers. This can be done in the add method on ArrayList. Each int must be added individually. For example, consider an int array. It has 3 values in it. We create an ArrayList and add those int as Integers in a for-loop.
The add() method receives an Integer. And we can pass an int to this method—the int is cast to an Integer.
List of Primitive Integer Values in Java
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We’re looking for a new Java technical editor to help review new articles for the site.
1. Overview
In this tutorial, we’ll learn how to construct a list containing primitive integer values.
We’ll explore solutions using core Java and external libraries.
2. Autoboxing
In Java, generic type arguments must be reference types. This means we can’t do something like List .
Instead, we can use List and take advantage of autoboxing. Autoboxing helps us use the List interface as if it contained primitive int values. Under the hood, it is still a collection of Objects and not primitives.
The core Java solution is just an adjustment to be able to use primitives with generic collections. Moreover, it comes with the cost of boxing and unboxing conversions.
However, there are other options in Java and additional third-party libraries that we can use. Let’s see how to use them below.
3. Using the Stream API
Oftentimes, we don’t actually need to create a list as much as we just need to operate on it.
In these cases, it might work to use Java 8’s Stream API instead of creating a list altogether. The IntSream class provides a sequence of primitive int elements that supports sequential aggregate operations.
Let’s have a quick look at an example:
IntStream stream = IntStream.of(5, 10, 0, 2, -8);
The IntStream.of() static method returns a sequential IntStream.
Similarly, we can create an IntStream from an existing array of ints:
int[] primitives = ; IntStream stream = IntStream.of(primitives);
Moreover, we can apply the standard Stream API operations to iterate, filter and aggregate the ints. For example, we can calculate the average of the positive int values:
OptionalDouble average = stream.filter(i -> i > 0).average();
Most importantly, no autoboxing is used while working with the streams.
Though, if we definitely need a concrete list, we’ll want to take a look at one of the following third-party libraries.
4. Using Trove
Trove is a high-performance library which provides primitive collections for Java.
To setup Trove with Maven, we need to include the trov4j dependency in our pom.xml:
With Trove, we can create lists, maps, and sets.
For instance, there is an interface TIntList with its TIntArrayList implementation to work with a list of int values:
TIntList tList = new TIntArrayList();
Even though TIntList can’t directly implement List, it’s methods are very comparable. Other solutions that we discuss follow a similar pattern.
The greatest benefit of using TIntArrayList is performance and memory consumption gains. No additional boxing/unboxing is needed as it stores the data inside of an int[] array.
5. Using Fastutil
Another high-performance library to work with the primitives is Fastutil. Let’s add the fastutil dependency:
IntArrayList list = new IntArrayList();
The default constructor IntArrayList() internally creates an array of primitives with the default capacity of 16. In the same vein, we can initialize it from an existing array:
int[] primitives = new int[] ; IntArrayList list = new IntArrayList(primitives);
6. Using Colt
Colt is an open source, a high-performance library for scientific and technical computing. The cern.colt package contains resizable lists holding primitive data types such as int.
The primitive list that offers this library is cern.colt.list.IntArrayList:
cern.colt.list.IntArrayList coltList = new cern.colt.list.IntArrayList();
The default initial capacity is ten.
7. Using Guava
Guava provides a number of ways of interfacing between primitive arrays and collection APIs. The com.google.common.primitives package has all the classes to accommodate primitive types.
For example, the ImmutableIntArray class lets us create an immutable list of int elements.
Let’s suppose, we have the following array of int values:
We can simply create a list with the array:
ImmutableIntArray list = ImmutableIntArray.builder().addAll(primitives).build();
Furthermore, it provides a list API with all the standard methods we would expect.
8. Conclusion
In this quick article, we showed multiple ways of creating lists with the primitive integers. In our examples, we used the Trove, Fastutil, Colt, and Guava libraries.
As usual, the complete code for this article is available over on GitHub.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
Why an ArrayList in Java cannot contain primitives like int , double or char
In Java, an ArrayList is a very convenient object that allows us to create and manage variable-length arrays. However, in Java, an ArrayList also has a weird quirk. You cannot declare an ArrayList that uses Java primitives. Below are a few examples:
import java.util.ArrayList; public class ArrayListTest < public static void main(String[] args) < ArrayList intList = new ArrayList(); ArrayList doubleList = new ArrayList(); ArrayList charList = new ArrayList(); > >
What’s the solution?
To create an ArrayList with primitives, you will need to use classes that box these primitives inside an object. Hence, for the above example:
import java.util.ArrayList; public class ArrayListTest < public static void main(String[] args) < ArrayListInteger> intList = new ArrayListInteger>(); ArrayListDouble> doubleList = new ArrayListDouble>(); ArrayListCharacter> charList = new ArrayListCharacter>(); > >
Even though these boxed primitives are objects, you can use them as though they are primitives, as Java does automatic boxing and unboxing of these primitives. For example:
import java.util.ArrayList; public class BoxedPrimitivesTest < public static void main(String[] args) < Integer a = 10; // You can treat this as though it is a primitive. int b = 25; System.out.println(a + b); > >
Article continues after the advertisement:
Below is a list of all 8 primitives in Java, as well as their boxed variants:
Primitive Type | Boxed Class | ArrayList initialiser |
---|---|---|
byte | Byte | ArrayList |
short | Short | ArrayList |
int | Integer | ArrayList |
long | Long | ArrayList |
float | Float | ArrayList |
double | Double | ArrayList |
char | Character | ArrayList |
boolean | Boolean | ArrayList |
As you can see, most of the boxed types use the same word as the primitive, with the first letter capitalised. The only exceptions to these are the int and char types, which are properly spelt out as Integer and Character respectively.
Why does this happen?
If you’ve tried out other languages similar to Java, you may find that not all of them have this quirk. C#, for example, allows their variant of the ArrayList to use primitives:
using System.Collections; class TestClass < static void Main(string[] args) < List intList = new List(); > >
This is because C# allows the use of primitive types in their generic functions, whereas Java does not, and the constructor for an ArrayList is a generic function. According to ChatGPT:
In Java, ArrayLists cannot directly hold primitive types because the Java Generics system only supports reference types as type parameters.
The Java Generics system was designed to provide compile-time type safety and facilitate code reuse by working with reference types. To work around this limitation, Java introduced auto-boxing and auto-unboxing. Auto-boxing allows automatic conversion between primitive types and their corresponding wrapper classes (e.g., int to Integer), while auto-unboxing performs the reverse operation.
To be frank, I don’t know what all of that means, but as long as you know how to use boxed primitives in Java, you should be fine.
Feel free to sound out in the comments below if you have anything to add.
Article continues after the advertisement: