public ArrayList<Integer> onlyPrimes(int[] numbers) {
    ArrayList<Integer> primes = new ArrayList<Integer>();
    …
}

my mind can’t wrap around what is happening with these 2 lines

I can understand your confusion. There is a lot going on in those two lines.

Line # 1

The first line defines the signature of a method. The name of the method will be onlyPrimes. This method will return a reference to an object, an instance of the class ArrayList (or return a null). The ArrayList object will contain zero, one, or more elements, each element being a reference to an object of the class Integer. When a programmer calls this onlyPrimes method, she will pass an array ([]) of primitive int values (or pass a null). Within the body of our onlyPrimes method, this passed array will be known as numbers.

By this declaration, any calling programmer knows that if they hand over an array of primitive int values, they get back a collection of Integer objects.

You may be getting especially confused by the fact that Java has two parallel type systems: primitives and objects:

  • Java was intended to be a thoroughly object-oriented language.
  • The primitives type system was also put into Java to (a) make learning easier to the majority of programmers then who were used to C-like languages, and (b) facilitate porting C code into Java.

The two type systems (objects & primitives) are bridged by auto-boxing with wrapper classes such as Integer for int.

Line # 2

The next line is the first line in the body of our method named onlyPrimes. Notice how I corrected your indenting to make clear this relationship between (a) the declaration of a method, and (b) the body of that method. The { curly-brace marks the opening of the body of the declared method.

This first line of the method body declares an object reference variable named primes. That variable shall hold a reference to an instance of the class ArrayList. This instance is a collection of objects of the class Integer. The EQUALS sign assigns an object reference to our variable primes.

The code after the EQUALS sign instantiates a new collection, an object of the class ArrayList. That collection is empty, holding no elements, but is capable of holding references to objects of the class Integer. The instantiation returns a reference to the new collection object. That reference is assigned as the content of the object reference variable we declared with name of primes.

Tutorials

I suggest you study a simpler tutorial that goes over the various parts of this code.

  • A good place to start is The Java Tutorials, by Oracle Corp, provided free of cost.
  • Another excellent tutorial is the book Head First Java, 3rd Edition by Kathy Sierra, Bert Bates, Trisha Gee.

Improving that code

I would make some changes to that code.

I would mark the method parameter as final to ensure that in the method body no other reference is assigned to numbers.

The passed argument should be validated, to be sure the calling programmer did not pass a null. A handy way to make this check is a call to Objects.requireNonNull.

We needn’t repeat the Integer as the type of the list in the second line. The compiler in modern Java can deduce that type. So just use <>.

Generally it is best to use the highest possible superclass or superinterface that offers the needed functionality. The superinterface of ArrayList is List. In Java 21 and later, an even higher superinterface is SequencedCollection (see JEP 431).

I am one of those folks who thinks it generally best to return an unmodifiable collection. So after populating the ArrayList, I would generate a new unmodifiable List by calling List.copyOf.

I would let the text of the code breathe, adding some SPACE characters. The crammed-together style is a historical artifact dating back to the 80-column limits of punched cards and terminals.

public SequencedCollection < Integer > onlyPrimes( final int[] numbers ) {
    Objects.requireNonNull( numbers ) ;
    SequencedCollection < Integer > primes = new ArrayList<>();
    …
    return List.copyOf( primes ) ;
}
Answer from Basil Bourque on Stack Overflow
Top answer
1 of 1
2
public ArrayList<Integer> onlyPrimes(int[] numbers) {
    ArrayList<Integer> primes = new ArrayList<Integer>();
    …
}

my mind can’t wrap around what is happening with these 2 lines

I can understand your confusion. There is a lot going on in those two lines.

Line # 1

The first line defines the signature of a method. The name of the method will be onlyPrimes. This method will return a reference to an object, an instance of the class ArrayList (or return a null). The ArrayList object will contain zero, one, or more elements, each element being a reference to an object of the class Integer. When a programmer calls this onlyPrimes method, she will pass an array ([]) of primitive int values (or pass a null). Within the body of our onlyPrimes method, this passed array will be known as numbers.

By this declaration, any calling programmer knows that if they hand over an array of primitive int values, they get back a collection of Integer objects.

You may be getting especially confused by the fact that Java has two parallel type systems: primitives and objects:

  • Java was intended to be a thoroughly object-oriented language.
  • The primitives type system was also put into Java to (a) make learning easier to the majority of programmers then who were used to C-like languages, and (b) facilitate porting C code into Java.

The two type systems (objects & primitives) are bridged by auto-boxing with wrapper classes such as Integer for int.

Line # 2

The next line is the first line in the body of our method named onlyPrimes. Notice how I corrected your indenting to make clear this relationship between (a) the declaration of a method, and (b) the body of that method. The { curly-brace marks the opening of the body of the declared method.

This first line of the method body declares an object reference variable named primes. That variable shall hold a reference to an instance of the class ArrayList. This instance is a collection of objects of the class Integer. The EQUALS sign assigns an object reference to our variable primes.

The code after the EQUALS sign instantiates a new collection, an object of the class ArrayList. That collection is empty, holding no elements, but is capable of holding references to objects of the class Integer. The instantiation returns a reference to the new collection object. That reference is assigned as the content of the object reference variable we declared with name of primes.

Tutorials

I suggest you study a simpler tutorial that goes over the various parts of this code.

  • A good place to start is The Java Tutorials, by Oracle Corp, provided free of cost.
  • Another excellent tutorial is the book Head First Java, 3rd Edition by Kathy Sierra, Bert Bates, Trisha Gee.

Improving that code

I would make some changes to that code.

I would mark the method parameter as final to ensure that in the method body no other reference is assigned to numbers.

The passed argument should be validated, to be sure the calling programmer did not pass a null. A handy way to make this check is a call to Objects.requireNonNull.

We needn’t repeat the Integer as the type of the list in the second line. The compiler in modern Java can deduce that type. So just use <>.

Generally it is best to use the highest possible superclass or superinterface that offers the needed functionality. The superinterface of ArrayList is List. In Java 21 and later, an even higher superinterface is SequencedCollection (see JEP 431).

I am one of those folks who thinks it generally best to return an unmodifiable collection. So after populating the ArrayList, I would generate a new unmodifiable List by calling List.copyOf.

I would let the text of the code breathe, adding some SPACE characters. The crammed-together style is a historical artifact dating back to the 80-column limits of punched cards and terminals.

public SequencedCollection < Integer > onlyPrimes( final int[] numbers ) {
    Objects.requireNonNull( numbers ) ;
    SequencedCollection < Integer > primes = new ArrayList<>();
    …
    return List.copyOf( primes ) ;
}
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › ArrayList.html
ArrayList (Java Platform SE 8 )
October 20, 2025 - Java™ Platform Standard Ed. 8 ... public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable · 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.
Discussions

Using methods from an ArrayList Java - Stack Overflow
I am trying to use the Methods from a class that i have in an Array list. The ArrayList is ArrayList With Appliance being a super Class. the ArrayList contans objects that extends Appliance such ... More on stackoverflow.com
🌐 stackoverflow.com
Putting methods into an ArrayList Java - Stack Overflow
I get a compiling error when I'm trying to add to the ArrayList (above): ... I'm fairly new to Java, so still learning. EDIT: This will eventually be a multiple choice quiz. I essentially want to the put the methods into an array so I can chose methods randomly. More on stackoverflow.com
🌐 stackoverflow.com
How do I create a 2d ArrayList in java?
Fast and easy solution: You can make an arraylist of an object which is of type arraylist More on reddit.com
🌐 r/learnjava
16
26
June 25, 2020
MOOC Intro Java Course Exercise 62 (Using methods to remove items from an ArrayList): MOOC gave me a void type method to do the removing; why don't I need a return value?

Post your code so it's easier to understand what you're talking about.

More on reddit.com
🌐 r/learnjava
8
3
June 1, 2017
🌐
InterviewBit
interviewbit.com › java-interview-questions
150+ Core Java Interview Questions and Answers | Freshers & experienced
ArrayList is implemented in such a way that it can grow dynamically. We don't need to specify the size of ArrayList. For adding the values in it, the methodology it uses is -
Published   January 25, 2026
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › List.html
List (Java Platform SE 8 )
October 20, 2025 - The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example).
🌐
W3Schools
w3schools.com › java › java_ref_arraylist.asp
Java ArrayList Methods
Some methods use the type of the ArrayList's items as a parameter or return value. This type will be referred to as T in the table. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
🌐
Oracle
docs.oracle.com › en › java › javase › 24 › docs › api › java.base › java › util › ArrayList.html
ArrayList (Java SE 24 & JDK 24)
July 15, 2025 - public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable · 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.
🌐
MalwareTips Forums
malwaretips.com › forums › guides › programming guides & questions
Guide | How To - ArrayList in Java (simple examples and quick tutorial) | MalwareTips Forums
December 17, 2018 - Hello guys, as I said I will talk about ArrayList in Java. ArrayList are a more sophisticated structure than arrays, but they are a bit different than the arrays. When you initialize an ArrayList variable you don't have to specify the length of the ArrayList, it is a flexible data structure...
Find elsewhere
🌐
Quora
quora.com › How-do-you-use-Java-ArrayList
How to use Java ArrayList - Quora
Answer: We can use to store elements in arraylist, it will grow size dynamically. it is storing elements based index number. so we can access element based on index, we can replace element based on index, we can search element based on index. ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › arraylist-in-java
ArrayList in Java - GeeksforGeeks
It implements List Interface which is a sub-interface of Collection Interface. Java provides multiple constructors to create an ArrayList based on different requirements: Creates an empty ArrayList with default initial capacity.
Published   1 month ago
🌐
Coderanch
coderanch.com › t › 672505 › java › ArrayList-Subclass-Methods
ArrayList and Subclass Methods (Beginning Java forum at Coderanch)
November 7, 2016 - Also in terms of generic feedback on coding conventions: - Your methods DogMethod and CatMethod should start with a lower case letter: dogMethod/catMethod - When declaring variables prefer the interface over the implementation. So instead of declaring an ArrayList, just declare a List i.e.
🌐
GeeksforGeeks
geeksforgeeks.org › java › arraylist-get-method-java-examples
ArrayList get(index) Method in Java with Examples - GeeksforGeeks
December 10, 2024 - Example 1: Here, we will use the get() method to retrieve an element at a specific index in an ArrayList of integers. ... // Java program to demonstrate the working of // get() method in ArrayList import java.util.ArrayList; public class GFG { public static void main(String[] args) { // Creating an ArrayList of Integers ArrayList<Integer> arr = new ArrayList<Integer>(3); // Adding elements to the ArrayList arr.add(10); arr.add(20); arr.add(30); System.out.println("" + arr); // Getting the element at index 2 int e = arr.get(2); System.out.println("The element at index 2 is " + e); } }
🌐
Programiz
programiz.com › java-programming › library › arraylist
Java ArrayList Methods | Programiz
Java has a lot of ArrayList methods that allow us to work with arraylists. In this reference page, you will find all the arraylist methods available in Java.
🌐
JavaGoal
javagoal.com › home › arraylist in java
arraylist in java and java arraylist methods - JavaGoal
March 14, 2023 - In Java, both the for loop and iterator can be used to iterate over an ArrayList, but the performance of these two approaches depends on the size of the ArrayList. A for loop is simple to use and provides easy access to elements by index.
🌐
BeginnersBook
beginnersbook.com › 2013 › 12 › java-arraylist
ArrayList in Java With Examples
You can use the set method to change an element in ArrayList. You need to provide the index and new element, this method then updates the element present at the given index with the new given element. In the following example, we have given the index as 0 and new element as “Lucy” in the ...
🌐
TutorialsPoint
tutorialspoint.com › home › java/util › java arraylist
Java ArrayList
September 1, 2008 - Following is the declaration for java.util.ArrayList class − · public class ArrayList<E> extends AbstractList<E> implements Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess · Here <E> represents an Element. For example, if you're building an array list of Integers then you'd initialize it as · ArrayList<Integer> list = new ArrayList<Integer>(); This class inherits methods from the following classes −
🌐
W3Schools
w3schools.com › java › ref_arraylist_iterator.asp
Java ArrayList iterator() Method
Java OOP Java Classes/Objects Java Class Attributes Java Class Methods Java Class Challenge Java Constructors Java this Keyword Java Modifiers · Access Modifiers Non-Access Modifiers Java Encapsulation Java Packages / API Java Inheritance Java Polymorphism Java super Keyword Java Inner Classes Java Abstraction Java Interface Java Anonymous Java Enum ... Java Data Structures Java Collections Java List Java ArrayList Java LinkedList Java List Sorting Java Set Java HashSet Java TreeSet Java LinkedHashSet Java Map Java HashMap Java TreeMap Java LinkedHashMap Java Iterator Java Algorithms
🌐
Stack Overflow
stackoverflow.com › questions › 44357290 › putting-methods-into-an-arraylist-java
Putting methods into an ArrayList Java - Stack Overflow
What do you want the list to have in it after you've done this? ... @AbhishekAryan you technically can by using method references. The list would then be an ArrayList<Runnable> and you can add methods to it using mcQuestions.add(this:: questionFredricton). ... What's the goal of adding these methods to a list ? By using Java Reflection, you can get Method object and you can call this method on a Object but it is a bit difficult to use...
🌐
Runestone Academy
runestone.academy › ns › books › published › csawesome › Unit7-ArrayList › topic-7-2-arraylist-methods.html
7.2. ArrayList Methods — CSAwesome v1
ArrayList<Integer> list = new ArrayList<Integer>(); list.add(new Integer(5)); // this will only work in Java 7 list.add(5); // this will work in all Java versions · You can put any kind of objects into an ArrayList. Even instances of a class that you wrote. For example, here is an ArrayList of Students. An example of an ArrayList of Student objects. Add a new student with your name and info in it. There are actually two different add methods in the ArrayList class.
🌐
W3Schools
w3schools.com › java › java_arraylist.asp
Java ArrayList
Since ArrayList implements the List interface, this is possible. It works the same way, but some developers prefer this style because it gives them more flexibility to change the type later. For a complete reference of ArrayList methods, go to our Java ArrayList Reference.