Examples using ArrayList and generics

Available
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;
        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<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
        else
            odd.add(x);    // Add x to the collection of odd numbers
    }
}
2
Task
Java Syntax,  level 7,  lesson 8
unavailable
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
    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(18)
  • Popular
  • New
  • Old
You must be signed in to leave a comment
CristianLevel 8 , Bucharest
4 November, 10:54
Great!
KARAN BHOITELevel 12 , Nagpur
25 July, 00:50
please somebody tell me about this * for (Integer x : result) { } how this works i forgot...
P.B.Kalyan KrishnaLevel 7 , Guntur
28 July, 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, 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, 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.
JasonLevel 22 , Rancho Cucamonga
5 July, 00:03
I don't eve remember being taught that we can do this with for loops. Does anyone care to explain what the hell is going on here? // Use the array to fill the list for (int i = 0; i < data.length; i++) list.add(data[i]); were they planning on teaching us this at any point or just throwing it out there only for people with previous experience in coding to understand it?
AshikLevel 11 , Al Buraymi
14 July, 21:24
The array 'data' is being added to the ArrayList 'list'. For loop is used to travel through the 'data' array and add them to the 'list' ArrayList consecutively.
deanLevel 8 , Deutschland
21 May, 17:57
any explanation of the example 5 - merge lists - in specific: 1. addAll method is a built in method like a .add / .set or is it custom made that just not shown up in the example above? 2. what's the purpose of using Collections.addAll() ? 3. is it true as it says in the comments on line 14 that we can only use this loop in collections which means ArrayList is a collection? also what is it a collection, an object / data type or?
BerksonLevel 17 , Fortaleza
23 May, 00:40
First.. Sorry about the report. I click in it by mistake. 1. addAll() is a built in Static Method for the Class Collections. See Collections. 2. The purpose is to show the method and to fill the arrayList with the values shown as arguments. 3 We can use enhanced for with Collections and all classes that implement the Interface Collection. Object is the base class for all java objects. All java object inherit from Object. This is inheritance. Collection is a interface in java and some classes implement Collection to make use of polymorphism. It's better you read Thinking in java 4th edition. You will realize all this concepts better. It's a really big bunch of things. Many concepts to explain here.
HenkLevel 19 , Pretoria
25 April, 08:04
hi Why specify ... Integer x = list.get(i); instead of int x = list.get(i); ?
NikeshLevel 15 , Delhi
27 April, 06:19
Both will do same job. here Integer is used to show use of wrapper of int.
Renat MukhametshinLevel 13 , Pervouralsk
17 April, 08:49
coolest!
HashiramaLevel 26 , Port-Harcourt
17 January, 06:27
Dear Diego Thank you for your timely, purposeful and interesting tasks. Madara Uchiha
Fadi AlSaidiLevel 13 , Carrollton
8 December 2018, 14:55
am I missing something? I don't get where we used Generics at all!!!!
Daniel KnoxLevel 9 , Annfield Plain
9 December 2018, 09:55
I think specifing Integer as the exact type is generics
Fadi AlSaidiLevel 13 , Carrollton
9 December 2018, 16:02
Thanks Daniel. I had to google Generics to get a better understanding. I think the course was trying to explain Generics without going into more learning concepts. I tried explaining Generics in a different way, on the comment section, of the previous module.
HashiramaLevel 26 , Port-Harcourt
17 January, 06:10
ArrayList is a class that can accept objects of any type. That's what makes it an example of Generics. It's a type and has an inner type that can be any type the user specifies. And if no type is specified in the parameter then it will be open to accept any type that is passed to it. That's just how I understand it
Ashutosh SharmaLevel 8 , Delhi
21 March, 17:31
You are right, my friend