Wednesday, January 15, 2025
HomeProgrammingHow can I create a list of primitive integers in Java?

How can I create a list of primitive integers in Java?

In Java, you cannot create a list of primitive int directly because lists only support objects. To work with primitive integers, use their wrapper class Integer. Here’s how:

List intList = new ArrayList<>();
intList.add(10);
intList.add(20);
intList.add(30);

Java automatically converts between int and Integer using autoboxing. If you need better performance and want to avoid boxing, consider using IntStream from the java.util.stream package or TIntList from third-party libraries like Trove. Example with IntStream:

See also  How do I set a default colorscheme in Vim?"

List intList = IntStream.of(1, 2, 3).boxed().collect(Collectors.toList());

This allows you to handle primitive-like integers in lists.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x