Lesson 11 - Lists in Java

Java OOP Lists in Java

In the previous lesson, Getters and setters in Java, we talked about getters and setters in Java. Today, we're going to take a look at a collection that is smarter than an array. Mainly, because it allows us to add or remove items from it at will.

We've already mentioned the term "collection". A collection is a structure where multiple objects can be stored. There are lots of collections in Java designed for different purposes, and can be used in different ways. So far, we only know one collection - arrays. However, for future lessons, we need something smarter into which we can simply add and remove items during run-time. It would surely be useful to be able to manage a database of objects in memory. We know that an array has a constant size which is the price to be paid for its high speed. Now, let's go over ArrayLists which can be seen as an extension of the array data type.

ArrayList

The ArrayList type belongs to a group that we call generic collections. The term "genericity" will be fully explained in the collections course, yes, there is a full course dedicated to them. For now, just know that when we declare an ArrayList, we may specify the data type of the objects which will be stored in it. Let's keep it simple and make an ArrayList of numbers that we'll generate randomly in a lotto simulator application.

The lottery

The program will ask whether we want to generate another lot (number) and that will eventually be added to the ArrayList. If we won't want to lot anymore, the program will print the generated numbers in ascending order. We'll start by creating a new project, calling it ListLottery, and adding a Lottery class to it. The class will include an ArrayList of the Integer data type where the numbers will be stored.

We've encountered the Integer class which serves for storing whole numbers and basically wraps the int type. Only objects can be inserted into ArrayLists, that's one reason why there is also the Integer data type since we won't be able to store ints there. There is a reference "wrapper" for each primitive type in Java.

The List will be private and serve only as an internal storage of the class, so it won't be accessible from the outside. Here's how we declare an ArrayList:

ArrayList<Integer> numbers;

We specify the data type for generic collections in angle brackets. An ArrayList is an object, just like everything else. Next, we'll initialize the variable before using it:

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

Notice the brackets that indicate a constructor. We'll place the list into our class, along with the random generator - Random. In order to use an ArrayList, we have to add import java.util.ArrayList; at the beginning of the file. In the constructor, we'll initialize these fields:

import java.util.ArrayList;
import java.util.Random;

public class Lottery {
        private ArrayList<Integer> numbers;
        private Random random;

        public Lottery() {
                random = new Random();
                numbers = new ArrayList<Integer>();
        }

}

We will also add lot() and print() methods, where lot() will add a new random number to the list and return it and print() will return a string containing all the generated numbers, sorted and separated by spaces.

We already know how to generate random numbers from the lesson with the RollingDie object. This time, we'll generate numbers from 1 to 100. The number will be added to the ArrayList using the add() method:

public int lot() {
        Integer number = random.nextInt(100) + 1;
        numbers.add(number);
        return number;
}

Easy, right? The ArrayList collection is pretty complicated internally so I won't go into the "behind the scenes" details until later. Plus, one of the main reasons Java was made was to offer sophisticated components of high quality that are easy to use.

Printing the numbers will be even easier. To sort them, we'll use the sort() method on the Collections class. We're going to need to import java.util.Collec­tions. The method doesn't return anything, it just sorts our ArrayList inside.

public String print() {
        String s = "";
        Collections.sort(numbers);
        for (int i : numbers) {
                s += i + " ";
        }
        return s;
}

Done.

Let's move to main() and make it so the program allows the user to control the object using a while loop. We've already done something like this before, where we ask the user whether he wishes to calculate another problem. We did it in the calculator sample program in one of our first couple of lessons. The same idea applies here.

We'll control the program by entering the following options - 1, 2, 3 (lot another number, print, quit). We'll read them using scanner.nextLine() as Strings.

Scanner scanner = new Scanner(System.in);
Lottery lottery = new Lottery();
System.out.println("Welcome to our lottery program.");
String choice = "0";
// main loop
while (!choice.equals("3")) {
        // option list
        System.out.println("1 - Lot the next number");
        System.out.println("2 - Print numbers");
        System.out.println("3 - Quit");
        choice = scanner.nextLine();
        System.out.println();
        // reaction to choice
        switch (choice) {
                case "1":
                        System.out.println("You got a: " + lottery.lot());
                        break;
                case "2":
                        System.out.println("Numbers drawn: " + lottery.print());
                        break;
                case "3":
                        System.out.println("Thanks for using our Lotto program");
                        break;
                default:
                        System.out.println("Invalid option. Please, try again.");
                        break;
        }
}

Don't forget to import the Scanner class. You can leave all importing up to NetBeans, all you have to do is to click using the right mouse button and choose "Fix imports". You can also use the Ctrl + Shift + I keyboard shortcut.

The program flow is clear from the code. First of all, we set a default value so the loop could start. Then, we read an option from the keyboard. The string is processed by a switch and the program performs the appropriate action. If the user enters an invalid option, the default case prints a message that tells them to enter a valid option.

Console application
...
1 - Lot the next number
2 - Print numbers
3 - Quit
1
You got a: 52
1 - Lot the next number
2 - Print numbers
3 - Quit
1
1 - Lot the next number
2 - Print numbers
3 - Quit
1
1 - Lot the next number
2 - Print numbers
3 - Quit
2
Numbers drawn: 10 12 13 14 21 22 23 24 28 28 42 45 52 52 57 58 59 70 71 72 79 83 86 89
1 - Lot the next number
2 - Print numbers
3 - Quit

Now we have visually confirmed that we are able to continue and add more and more new numbers to the list. The ArrayList collection can do pretty much everything an array can do and much more. However, if we want, we could work with it similarly like we would with an array.

We can index using the get() and set() methods, but beware, there must be an item at that position in order for it to function properly:

ArrayList<String> l = new ArrayList<String>();
l.add("First");
System.out.println(l.get(0));
l.set(0, "First item");
System.out.println(l.get(0));
l.set(1, "Second item");  // causes an error

We create an ArrayList of Strings. We add the "first" item and then print an item at index 0, which will print "first". Of course, we can also write at that position; however, we can't work with the second item since we haven't added it to the List. When working with arrays, we have to specify its size and the array generates empty "boxes", indexed variables, for us. With ArrayLists, we don't specify the size and we add "boxes" manually.

Let's look at the ArrayList collection in detail and go over some of the methods it provides that we will use in the near future:

Constructors

We are not limited to adding single objects to ArrayLists. We could also create a copy of another ArrayList, array or any other type of collection. All we have to do is pass the collection to the constructor:

String[] stringArray = {"First", "Second", "Third"};
ArrayList<String> l = new ArrayList<String>(Arrays.asList(stringArray));
System.out.println(l.get(2));

The code will print "Third" and array items will be copied into the new ArrayList. Similarly, we could pass another ArrayList in the constructor and get the same results.

ArrayList methods

  • size() - Works as length does on an array, it returns the number of items in the collection.
  • add(item) - This method takes an item as a parameter and adds to the end of the list.
  • addAll(collec­tion) - Adds multiple items to the list, e.g. from an array.
  • clear() - Removes all items in the ArrayList.
  • contains(item) - Returns true/false depending on whether the ArrayList contains the given item.
  • indexOf(item) - Returns the index of the first occurrence of a given item in the list (like with an array). Returns -1 in case of failure.
  • lastIndexOf(item) - Returns the index of the last occurrence of a given item in the list. Returns -1 in case of failure.
  • remove(item) - Removes the first occurrence of an item.
  • removeAll(index, count) - Removes a specified number of items starting at a specific index.
  • toArray() - Copies the items from the ArrayList to a given array and returns it.

Other methods

We can find another methods for working with lists in the Collections class. They all take the collection as a parameter.

  • min() - Returns the smallest element.
  • max() - Returns the largest element.
  • reverse() - Works the same as it would in an array. It reverses the ArrayList so the first item is the last and vice versa. The method doesn't return anything, the changes are made directly to the List.
  • sort() - This method sorts the items in the ArrayList. The method doesn't return anything either.

Now we have seen that the ArrayList collection can do much more than arrays. The biggest advantage to it is being able to add and remove items. Drawbacks in the performance are insignificant to us now. In the collections course, we'll cover all of the other methods that ArrayList provides, but for now, the ones we covered today will suffice.

A number storing program is surely interesting, but it would be more useful to be able to store fully-featured objects instead of numbers. In the next 3 lessons, Date and Time in Java - Creating and formatting, we'll learn about date and time in Java. And then, we'll use ArrayList to create a database, specifically, an electronic diary! :)


 

 

Article has been written for you by David Capka
Avatar
Do you like this article?
No one has rated this quite yet, be the first one!
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn College The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.
Activities (3)

 

 

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!