Examples using ArrayList and generics

Examples using ArrayList and generics - 1

"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;

"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
            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>();


    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

"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<Integer> list = new ArrayList<Integer> ();

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

    ArrayList<Integer> even = new ArrayList<Integer>();  // Even numbers
    ArrayList<Integer> odd = new ArrayList<Integer>();    // 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
            odd.add(x);    // Add x to the collection of odd numbers
Java Syntax,  level 7lesson 8
Code entry
Your attention, please! Now recruiting code entry personnel for CodeGym. So turn up your focus, let your fingers relax, read the code, and then... type it into the appropriate box. Code entry is far from a useless exercise, though it might seem so at first glance: it allows a beginner to get used to and remember syntax (modern IDEs seldom make this possible).

"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

    for (Integer x : result)   // A fast way to loop over all elements, only for collections

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

"Yes, he will."

  • Popular
  • New
  • Old
You must be signed in to leave a comment
RoseLevel 7 , Richardson
yesterday, 18:12
Anyone had a problem in repeating the code I did it multiple times and still wrong. WHY?
Maxine HammettLevel 8 , San Diego
28 June, 20:44
Example 5 uses "collections" but it has not been introduced and explained. Very frustrating.
31 May, 23:36
I love the examples. Learning from examples is the best way to learn.
sarahLevel 0 , At Tafilah
24 February, 19:33
can someone please help me with this its urgent !!!Using Java 1)Give a complete implementation for the following method static void addAll(ArrayList<Integer> list1, ArrayList<Integer> list2) {} static void removeAll(ArrayList<Integer> list1, ArrayList<Integer> list2) {} static void retainAll(ArrayList<Integer> list1, ArrayList<Integer> list2) {} 2)In the main program, declare two Integer Arraylists, call the methods defined in part1 then show the results.
arun chandelLevel 12
19 February, 04:15
can some body please explain example 3 . how the loop forwards when i > 5 ?? the else part i++ will not be executed if i> 5 .so how the next element will be processed ??
SebLevel 41 , Crefeld
19 February, 09:41
That's a very good observation, Arun. The thing is that example 3 is a special case - elements with a value greater than five are deleted from the ArrayList. In the case that a value is actually greater than 5 - and thus is deleted - the loop counter may not be increased because the ArrayList now actually stores one element less and the items are shifted down by one element. For example - after the insertion of values into the list on lines 6 to 10 the list stores the elements [1, 7, 11, 3, 15]. (The index of these elements runs from 0 to 4.) When running the loop and we get to the second element (the number 7 at index 1), the check for greater than 5 is true and the element with the value 7 will be deleted from the list. The list now looks as follows [1, 11, 3, 15]. That means that after the removal of the element with value 7, the following elements were shifted down - say 11 now is not at index 2 anymore, but at index 1. Since we specifically did not increase the loop counter, the next round of the loop will still check the element at index 1, which now is 11. I hope that helps. Cheers Seb
AustejaLevel 10 , Kaunas
19 January, 11:52
Amazing <3
2 January, 14:03
CristianLevel 8 , Bucharest
4 November 2019, 10:54
KARAN BHOITELevel 15 , Nagpur
25 July 2019, 00:50
please somebody tell me about this * for (Integer x : result) { } how this works i forgot...
P.B.Kalyan KrishnaLevel 8 , Guntur
28 July 2019, 09:21
This just means for each 'x', which is an Integer object, from the Collection 'result', which is ArrayList, perform the following operations. This loop is called for..each loop and is very useful in iterating over Collections and arrays.
RafaelaLevel 10 , Dortmund
10 July 2019, 09:08
The Code Entry exercises are pretty buggy. When auto complete kicks in, the screen goes red and even stays red after all of the entered code is identical with the example. In my opinion, the Code Entry exercises can be left out anyway. If any human truly wants to code like a robot, they can mindlessly copy code in their free time. For me, I prefer to focus on the practical exercises. I don't see how humans are supposed to learn from brainless exercises like Cody Entry.
Glenn MeyerLevel 8 , Cleveland
14 November 2019, 16:32
I strongly disagree. It is important for the mechanical entry to occur to build some muscle memory and create some mental patterns to stick in your mind. Otherwise, simple things like "public static void main(String[] args)" will be easily forgotten. Secondly, 100% of the time I have initially failed a Code Entry exercise, it was because I had a typo somewhere, whether an missing ) or an extra . it was always my mistake. Not buggy if you typed it wrong, which is the whole point actually.
horstLevel 17
3 January, 20:36
I am not especially fond of the repetition tasks myself, but I value it as a different approach. The autocomplete "bug" does exist nevertheless. It occurs, for example, when you type opening brackets { and then hit return. The system will then automatically add closing brackets } two lines further down. This causes your code to be "wrong" until you actually reach the end of the block. Now you can either simply endure this, although it's more convenient to immediately be informed about typos while committing them. (Or obviously you can manually remove the auto-inserted bracket). But I think the most convenient way to handle it, is to press ctrl+z (undo) immediately after the system inserted the additional closing bracket. This will remove the additional bracket and let you hit return again without auto-inserting the bracket.