CodeGym /Courses /New Java Syntax /Examples using ArrayList and generics

Examples using ArrayList and generics

New Java Syntax
Level 13 , Lesson 4
Available

"How about I start with what's actually useful? You'll now see a couple of ways that ArrayList and generics can be put to work:"

"Example 1:"

Read a list of numbers from the keyboard
public static void main(String[] args) throws IOException
{
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in) );
    ArrayList<Integer> list = new ArrayList<Integer>() ;

    while (true)
    {
        String s = reader.readLine();
        if (s.isEmpty()) break;
        list.add(Integer.parseInt(s));
    }
}

"Example 2:"

Same as above, but even numbers are added to the end of the list, odd – to the beginning of it.
public static void main(String[] args) throws IOException
{
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    ArrayList<Integer> list = new ArrayList<Integer>();

    while (true)
    {
        String s = reader.readLine();
        if (s.isEmpty()) break;

        int x = Integer.parseInt(s);
        if (x % 2 == 0)  // Check that the remainder is zero when we divide by two
            list.add(x);         // Add to the end
        else
            list.add(0, x);      // Add to the beginning           
    }
}

"Example 3:"

Delete all numbers larger than 5:
public static void main(String[] args) throws IOException
{
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in) );
    ArrayList<Integer> list = new ArrayList<Integer>();

    list.add(1);
    list.add(7);
    list.add(11);
    list.add(3);
    list.add(15);

    for (int i = 0; i < list.size(); ) // We moved the statement that increases i to inside the loop 
    { 
        if (list.get(i) > 5)
            list.remove(i);  // Don’t increase i if we deleted the current element   
        else
            i++;
    }
}

"Example 4:"

Divide an array into two parts – even and odd numbers
public static void main(String[] args) throws IOException
{
    // Static initialization of the array
    int[] data = {1, 5, 6, 11, 3, 15, 7, 8};  

    // Create a list where all elements are Integers 
    ArrayList&ltInteger> list = new ArrayList&ltInteger> ();   

    // Use the array to fill the list
    for (int i = 0; i < data.length; i++) list.add(data[i]);  

    ArrayList&ltInteger> even = new ArrayList&ltInteger>();  // Even numbers
    ArrayList&ltInteger> odd = new ArrayList&ltInteger>();    // Odd numbers

    for (int i = 0; i < list.size(); i++)
    {
        Integer x = list.get(i);
        if (x % 2 == 0)    // If x is even
            even.add(x);   // Add x to the collection of even numbers  
        else
            odd.add(x);    // Add x to the collection of odd numbers
    }
}

"Example 5:"

Merge lists
public static void main(String[] args) throws IOException
{
    ArrayList<Integer> list1 = new ArrayList<Integer>();   // Create a list  
    Collections.addAll(list1, 1, 5, 6, 11, 3, 15, 7, 8);   // Fill the list

    ArrayList<Integer> list2 = new ArrayList<Integer>();
    Collections.addAll(list2, 1, 8, 6, 21, 53, 5, 67, 18);

    ArrayList<Integer> result = new ArrayList<Integer>();

    result.addAll(list1);   // Add all values from each list to the new list
    result.addAll(list2);

    for (Integer x : result)   // A fast way to loop over all elements, only for collections
    {
        System.out.println(x);
    }
}

"Cool! Will Diego now give me a truck load of similar exercises?"

"Yes, he will."

Comments (46)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Hoist Level 3, San Diego, United States
22 September 2022
Worthwhile to read _every_ answer / clarification here ... many useful perspectives not found in books
Aldo Luna Bueno Level 1, Peru
25 November 2021
Interesante. Casi ninguno de esos ejemplos se puede llevar a cabo de esa manera con los simples arreglos: necesitamos las listas. Con los ejemplos 1 y 2, nos damos cuenta de que ahora podemos ingresar elementos a una lista sin especificar cuántos son ni fijar previamente un tamaño suficiente. Con el 3, vemos que ahora podemos remover elementos sin dejar huecos. Con el 4, descubrimos que no tenemos que fijar en el código tamaños suficientes (data.length) para las listas en las que se distribuyen los elementos del arreglo «data». Con el 5, vemos lo simple que es sumar listas con respecto a lo que habría que hacer con arreglos.
Yuxi Zhou Level 9, New York, United States
15 October 2021
Heyy as for example 4, I'm really curious why we need to put the array elements into an ArrayList first, it's kinda redundant to me..thanks!
Justin Smith Level 41, Greenfield, USA, United States
10 July 2021
Example 3 has a really important piece of loop+arraylist logic to understand and I wish they explained it more clearly. When you remove an element from an Arraylist, it redesignates the indexes of all the elements above it. So if you delete list(0), then list(1) becomes list(0). That is why it's not automatically adding 1 to i each time it goes through the loop - it needs to check list(0) again because list(0) has changed. In many cases you can avoid this by iterating from top to bottom instead.
John Dangle Level 22, United States of America
27 August 2021
Thanks for the info!
Jomar Tayactac Level 5, Winnipeg, Canada Expert
26 October 2021
Could you explain how iterating from the top to bottom would prevent doing what you explained? Thanks.
Justin Smith Level 41, Greenfield, USA, United States
26 October 2021
Sure. Let's take example 3 to explain this. An alternate way of doing it:

    for (int i = list.size() - 1; i >= 0; i--)
    {
        if (list.get(i) > 5)
        {
            list.remove(i);
        }
    }
This works because when you remove an element from an ArrayList, it shifts only the elements that are of index higher than the one removed. If list.size() = 10, and we remove list.get(5), it changes the indexes of list.get(6) through list.get(9), but not of list.get(0) through list.get(4). So if you instead structure the for loop so that it only shifts elements that you have already checked in the loop, then you don't have this problem. So in this case, if we remove list.get(5), it's not an issue that elements 6 through 9 get shifted downward by 1, because they've already been handled.
Andrei Level 41
27 October 2020
Hello, I have a question regarding example 4:

        Integer x = list.get(i);
Why declare Integer x and not int ? Is it because Integer x has to store data from an ArrayList that stores Integer? Thanks!
Thomas Fuhrmann Level 25, Vienna, Austria
8 January 2021
In ArrayList only Integer is possible and not the primitive type int. So you'll have Integer for the type of x.
DarthGizka Level 24, Wittenberg, Germany
29 May 2021
Your answer didn't address Andrei's question at all. x could have been declared as a real int, not a boxed one (Integer), since boxed values and unboxed ones can be freely assigned among each other. Hence it would have been perfectly alright (and even preferrable) to write:

int x = list.get(i);
I agree with Andrei that the use of Integer instead of int for x is a fact that warrants an explanation. Perhaps they wanted to show that you can used boxed integers in expressions like x % 2 just like normal ones.
amj Level 7, Imphal , India
6 October 2020
what is the difference between int and Integer?
Java Learner Level 11, Herlev, Denmark
9 October 2020
int is a primitive type where as Integer is of class type. int does not have any built-in method since Integer is class type. it has built-in method supports
Karas Level 20, Tampa, United States
5 September 2020
I love the enhanced for loop in the last example! Thats the name of it: Enhanced for loop.
Shashikant Sharma Level 8, Surat, India
28 August 2021
It's Basically Called "For - Each Loop".
Agent Smith Level 38
14 August 2020
Example 3 is rather curious. Doest the for loop call list.size() on every iteration, so it is being updated every time? In the Java books I've read authors usually strongly discourage changing the size of the list/array if you are using its size as a loop condition, considering it as a bad practice and a possible source of bugs.
Emirhan Level 12, Amsterdam
18 August 2020
That's correct, it is being updated every time. However "i" only increases if nothing gets removed. In the case of a removal, "i" does not increase (so the loop repeats itself with the same value for "i"). For that reason, the loop won't give any errors. Hope this helps.
Rose Level 14, Richardson, United States
7 July 2020
Anyone had a problem in repeating the code I did it multiple times and still wrong. WHY?
Stephan Koch Level 8, Singapore, Singapore
20 January 2021
For future reference: I've faced a similar issue, you might have to scroll up since the window is not displaying all the code (depending on the resolution of your explorer).
Maxine Hammett Level 19, San Diego, United States
28 June 2020
Example 5 uses "collections" but it has not been introduced and explained. Very frustrating.
Onur Bal Level 27, Istanbul, Turkey
9 September 2020
It's all on purpose; the philosophy of CodeGym was explained a few levels back. Basically, new bits of information are first introduced inside of practices, so you encounter something new and foreign to you, and have to adapt on your own, perhaps making some research as you try to use it, or just going along with it as it is given. The theory is introduced only after getting the exercises done. This is actually a brilliant method for learning, because it's easier to learn the theory behind something if you already have hands-on practice with it, rather than trying to learn an abstract theory without having any idea what it all amounts to in real practice.
Gaelle Gilles Level 15, New York City, United States
1 January 2021
Just to add to what Onur said, so you can do some research on your own. There is a lot of information on Java and you can only learn so much from CodeGym. So this is a way to encourage you to do some research on your own so you won't depend on one source to learn this language. This website: https://docs.oracle.com/javase/8/docs/api/ has all of the classes and packages that Java programmers can use for free. It is the go-to website for programmers. You can find the list of Collections on this website if you want to browse and learn what is there.