Unit 11 Sorted and Ordered Collectiions Flashcards
Lists:-
Fixed size versus dynamic:
Lists are _____ sized.
Lists are dynamically sized.
A list will grow and shrink as elements are added or removed.
Lists:-
True or False
Ordering: Lists are unordered.
False
Lists are ordered. A list can be grown simply by tagging items on the end, in which case the elements will be in the order they were added. Alternatively an item can be inserted at a specified position
Lists:
True or False
Indexing: Every element in a list has an integer index 0, 1, 2, 3, … to indicate its position.
True
The index provides a way of directly accessing the element. If an item is inserted in the middle of a list then all the elements beyond it will be moved up to make space for it, so their indexes will increase by 1. If an item is removed from a list, all the elements beyond it will have their indexes decreased by 1, so the gap closes up
Lists:-
True or False
Duplicates: Like sets, which do not allow duplicates, a list can not contain any number of repeated elements.
False
Unlike sets, which do not allow duplicates, a list can contain any number of repeated elements.
Lists:-
Is List a sub interface of Collection or Map?
Collection
So Lists already inherit the Collection protocol such as add(), addAll(), remove(), clear(), size(), contains() and isEmpty()
Lists:-
Best practice is to use a variable declared as being of the interface type because that gives us flexibility to change our mind later about what implementation class we will use. What is a good general-purpose choice for a class that implements the List interface unless we know of a particular reason for using another list class?
an ArrayList
Lists:-
Using the same style declaration as Set and Map, declare a list, with variable “hoverFrogList” to hold instances of class HoverFrog.
List < HoverFrog > hoverFrogList = new ArrayList < > ( );
Lists:-
As with other collections you have seen, one of the simplest things you can do with a list is to get its size. The size of a list is simply the number of elements it contains. (Note that the elements of a list may include the value null and that any occurrences of null will be counted in the size.) Declare a list, with variable herbList to hold instances of String. You can create a local variable size, which holds primitive int values and print out “Size of newly created list is: “ followed by the size of the list.
List < String > herbList = new ArrayList < > ( );
int size =herbList.size();
System.out.println(“Size of newly created list is: “+size);
Lists:-
Given
List < String > herbList = new ArrayList < > ( );
Add three string elements, Parsley, Sage and Rosemary to an initially empty set, making the size 3. The elements are stored in the order they are added, beginning with index 0.
herbList.add(“Parsley”);
herbList.add(“Sage”);
herbList.add(“Rosemary”);
- Size after adding elements:*
- 3*
- Parsley*
- Sage*
- Rosemary*
Lists:-
If we run the following code, what is the size of the List?
List < String > herbList = new ArrayList < > ( );
herbList.add(“Parsley”);
herbList.add(“Sage”);
herbList.add(“Rosemary”);
herbList.add(“Rosemary”);
herbList.add(“Rosemary”);
int size =herbList.size();
System.out.println(“Size of this list is: “ +size);
- Size of this list is: 5*
- Parsley*
- Sage*
- Rosemary*
- Rosemary*
- Rosemary*
Unlike a set, a list can contain duplicate elements, as the code demonstrates. Five elements are added to the list, but three of those elements are duplicates. The size of the list is nevertheless 5.
Lists:-
An element can be inserted at any index by using an add() message that takes two arguments(the first being the index in the list, the second being the object to add at that index).
Given;
List < String > sandwich = new ArrayList < > ( );
(a) Add the following elements “Bottom slice” and “Top slice”
(b) Now add the element “Filling” so it will appear in the list as the middle element
(a)
sandwich. add(“Bottom slice”);
sandwich. add(“Top slice”);
(b) sandwich.add(1, “Filling”);
The key point here is that when “Filling” is placed at index 1, “Top slice” (which was at index 1) is moved up to position 2. Bottom slice Filling Top slice Note that when we iterate through a list we start from index 0, which we would consider to be at the bottom of the list, and so, when printed out, the sandwich seems to be upside down.
Lists:-
If a List has a size 3 “Bottom Slice”, “Filling” and “Top slice” and an element is added at index 4, what happens?
Also,what about trying to add at index -1 ?
An attempt to add this element beyond the end of the current list, will fail. An exception occurs: java.lang.IndexOutOfBoundsException
Attempting to add an element at-1 also generates an exception; A negative index is illegal.
Lists:-
The intention is that the method will store six string elements in an instance of ArrayList and then print them out to produce the well-known phrase ‘To be or not to be’. The code that inserts the elements is missing at present and you are invited to supply it. Of course, you cannot perform the task simply by adding elements in this order to the end of the list. To get the strings into the necessary order, some elements will have to be inserted at specific indices.
List < String > phrase = new ArrayList < > ( );
phrase. add (“be”);
(a) continue to add the strings to the list in sequence “To”, “or”, “be”, “not” and finally “to”.
(b) now, using a for-each statement, print elements all on one line, separated by spaces.
List < String > phrase = new ArrayList < > ( );
phrase. add (“be”);
phrase. add(0,“To”);
phrase. add(“or”);
phrase. add(“be”);
phrase. add(3, “not”);
phrase. add(4, “to”);
for ( String eachElement : phrase)
{
System.out.print(eachElement +” “);
}
Lists:-
Accessing the element at a specified position in a list is straightforward.
Using the code below, write more code to return “Parsley”
List < String > herbList = new ArrayList < > ( );
herbList.add(“Sorrel”);
herbList.add(“Tansy”);
herbList.add(“Parsley”);
herbList.add(“Rosemary”);
String selected = ____________________
herbList.get(2);
Lists:-
Removing a specified element from a list is a little different from removing a specified element from a set because a list can have duplicate elements. So it is possible to remove an element from a list, reducing the size of the list by one, while other instances of the element remain. Does removing an element leave an empty space with a value “null” or instead will the elements beyond the one removed move down one position to close the gap?
The elements beyond the one removed, move down one position to close the gap.
Lists:-
In the following uncompleted code, remove the third element, “Rosemary” and state the elements the System.out.print would read
List < String > herbList = new ArrayList ( );
herbList.add(“Sorrel”);
herbList.add(“Tansy”);
herbList.add(“Parsley”);
herbList.add(“Rosemary”);
herbList.add(“Rosemary”);
herbList.add(“Sage”);
String removed =_______________;
System.out.println(“The herbList contains the following elements in the following order: “);
for (String eachElement : herbList)
{
System.out.print(eachElement +” “);
}
herbList.remove(3);
would remove “Rosemary” from the list at index 3, and the list would then contain the following elements, in the following order: “Sorrel”, “Tansy”, “Parsley”, “Rosemary”, “Sage”
Lists:-
Given;
List < String> herbList = new ArrayList ( );
herbList.add(“Oregano”);
herbList.add(“Oregano”);
herbList.add(“Basil”);
herbList.add(“Rosemary”);
herbList.add(“Rosemary”);
herbList.add(“Rosemary”);
This question is to understand and practice the methods indexOf() and lastIndexOf()
The completed code will return an int value for the variables position1, position2, position3 and position4.
Using the methods indexOf() or lastIndexOf() complete the code:-
int position1 = herbList._____(“Oregano”); //position1 needs to assign the value 0,
int position2 = herbList._____(“Sorrel”); //position2 to assign the value -1
int position3 = herbList._____(“Rosemary”); //position3 to assign the value 5
int position4 = herbList._____(“Parsley”); //position4 to assign the value -1
int position1 =herbList.indexOf(“Oregano”);
int position2 =herbList.indexOf(“Sorrel”);
int position3 = herbList.lastIndexOf(“Rosemary”);
int position4 =herbList.lastIndexOf(“Parsley”);
position2 and position4 can use indexOf() or lastIndexOf() message as both return -1 as Sorrel and Parsley are not in the herbList
Lists:-
The element at a given position can be replaced by a new one. This is not the same as inserting an element, which increases the size of the list. When replacing an element the size stays the same and one of the original elements is overwritten by the new one.
Given;
List < String > herbList = new ArrayList < > ( );
herbList.add(“Parsley”);
herbList.add(“Sage”);
herbList.add(“Rosemary”);
herbList.add(“and”);
herbList.add(“Thyme”);
change the above code, herbList so it ends up holding the following elements, in the following order: “Are”, “you”, “going”, “to”, “Scarborough Fair”
herbList.set(0, “Are”);
herbList.set(1, “you”);
herbList.set(2, “going”);
herbList.set(3, “to”);
herbList.set(4, “ScarboroughFair”);
Lists:-
Will this code compile and run?
for (int herbIndex =0; herbIndex < herbList.size( ); herbIndex++)
{
System.out.println(herbList.get(herbIndex) +” is at index “ +herbIndex);
}
A for-each loop will iterate through a list, in index order. This gives access to the elements but not to the index. If there was a reason to access the index, we could use an ordinary for loop and iterate using the index and the message get() This second type of iteration is possible only because lists have an integer index; it cannot be used with sets and maps.
Lists:-
FROG to TOAD Riddle:
Print out the following, by completing the code:
FROG
FOG
LOG
LAG
LAD
LOAD
TOAD.
List < String > word = new ArrayList < > ( );
word. add(“F”);
word. add(“R”);
word. add(“O”);
word. add(“G”);
System.out.println(word);
//continue to change word from FROG to FOG, etc
word.remove(1);
System.out.println(word); //FOG word.set(0,”L”) System.out.println(word); //LOG word.set(1,”A”); System.out.println(word); //LAG word.set(2,”D”); System.out.println(word); //LAD word.add(1, “O”); System.out.println(word); //LOAD word.set(0,”T”); System.out.println(word);
Arrays vs ArrayList:-
It is possible to start with a list and create an equivalent array – containing the same elements in the same order – by sending it the message toArray() .Is it also possible to start with an array and produce a list, using a static method of the utility class Arrays. (You met the utility class Arrays in Unit 9.)
Yes, and here is how it is done:
String [] sArray = {“The”, “cat”, “sat”, “on”, “the”, “mat”};
List < String > stringList = Arrays.asList(sArray);
Array vs Collection:-
try to decide what sort of structure might be best to model the following practical problems. Would it be best to use a collection class? If so what interface would that class implement? Or would an array be all that is required?
In each case try to give the element or component type (using Java library classes) as well as a description.
(a) A programmer wants to store the names of the days of the week as strings and access them by day number, starting with Sunday as day zero.
(b) A secretary wants to store the telephone numbers of the members of a focus group and retrieve a person’s number given their name.
(c) A doctor wants to keep a record of the names of patients visited out of hours.
(d) A geographer wants to record the heights of mountains in metres and find the height of a mountain given its name.
(e) A classical scholar wants to record all the distinct Latin words that occur in the surviving works of Horace.
(f) A restaurant manager wants to store a menu of the currently available dishes. The list is to be numbered for the convenience of customers ordering food for home delivery. The particular offerings on the menu may alter from time to time as the restaurant tries out new dishes or discontinues ones that have not proved popular enough.
(g) A travel agent wants to be able to record the names of winter holiday resorts and the names of the hotels at each resort, and look up the hotels at a given resort.
Remember to say array or collection type and element type i.e., String, integer…
(a) Programmer (days of week) - This is a cast-iron case for an array. The requirements are very simple. The size is known in advance to be 7 and will never change. The contents, once set, will never need to be altered. All we will ever need to do is access the items by day number, handily starting from 0, so the obvious thing to do is make the day number the array index. The component type would be String. In fact,there is a better option in this case, an enum. These are not covered in M250, but if interested, read Oracle’s Java tutorials.
(b) Secretary (focus group) - We must be able to find the number given the name, so a collection class that implements the Map interface is needed here, with the name as the key and the number as the value. The element type would be < String, String >, i.e. both the keys and the values would be strings. (Telephone numbers cannot conveniently be stored as integers, because a leading zero is significant.)
(c) Doctor (patient visits) - This looks like a list of names without a fixed size and allowing duplicates, since a particular patient may have been visited several times and we want to record all the visits, so some names will be repeated. A collection class that implements the List interface is needed here. The element type would be String.
(d) Geographer (height of mountains) - Again it looks as though we need a collection class that implements the Map interface, with the name of the mountain as the key and the height as the value. A suitable element type would be < String, Integer >, i.e. the keys would be strings and the values would be integers.
(e) Scholar (Horace) - The scholar does not want to know how many times each word appears or anything like that; but simply to list the vocabulary used, and each word should appear only once. So a collection class that implements the Set interface would be suitable, because it does not allow duplicates. In fact, since the word list will need to be sorted, we could use the TreeSet class that we met briefly in Unit 10. The element type would be String.
(f) Restaurant (current dishes) - The menu items are numbered. Dishes may be added or taken off, so the size of the menu can vary. New dishes will probably get inserted amongst existing ones, and when dishes are removed that section of the menu will contract. From the description it sounds as though a collection class that implements the List interface would be best, with the type of the elements being String.
(g) Travel Agent (winter resorts) - This is more complex. To record the names of the hotels at any particular resort a set would be suitable. The number of hotels at that resort can vary from year to year, they are probably not recorded in any special order, and no hotel ought to appear more than once – if it did, that would be a mistake. All these considerations suggest using a class that implements the Set interface. We also note that the travel agent needs to be able to find the names of the hotels given the name of a resort. This suggests we also need a collection class that implements the Map interface, with the resort names as keys and the values being the sets of hotel names. So the element type would be < String, Set < String > >
Element Types:-
Instead of using String or integer as the element type, a programmer might design classes such as TelephoneNumber, Patient, Mountain, Dish, Resort or Hotel to represent the objects in the collections.
- It allows the programmer to provide methods that are more suited to the class concerned - overridding;
- methods that are useful for the class of objects can be written;
- stricter type checking will be enforced when the code is compiled.
Give examples using the above bullet points of why writing a bespoke class is a better strategy
This question is more of a reminder than to test your knowledge.
- It allows the programmer to provide methods such as equals() and toString() that are suitable for the class concerned;
- methods that are useful for the class of objects can be provided (for example, a TelephoneNumber class might have a method getAreaCode( ));
- stricter type checking will be enforced when the code is compiled (eg, the compiler would not allow a String to be added to a collection whose element type is TelephoneNumber).
Lists:-
Can a list be sorted?
As you have seen, lists are ordered collections. The elements are stored in the order given by their indexes, and if we iterate through a list, this is the order that is followed. However, the order does not have to reflect anything to do with the elements themselves. It is simply determined by where each element has been placed in the list. There is no general reason to expect that the elements in a list will automatically be in alphabetical or numerical order. For example, the elements in a list of herbs might have been added just in the order they occurred to us;
parsley, basil, thyme, camomile, fennel, …
This leads to the question: can lists be sorted?
Eg, can we put our list of herbs into alphabetical order?
basil, camomile, fennel, parsley, thyme, …
Yes
The class Arrays does not have a sort() method for lists, but, the utility class Collections also has many static methods for working with collections.
Reverse, swap, sort, shuffle, sublists, max and min…
Lists:-
Reversing
To reverse a list, pass it as an argument.
Write the one line code to reverse the order of the elements in herbList from the variable Collections.
Collections.reverse(herbList);
Note this and several other methods are destructive – they modify the original collection. If you do not want this to happen you will need to create a copy of the collection and work with that instead.
Lists:-
Sorting
If the elements in a list have a natural ordering (e.g. alphabetical order for strings or numerical order for numbers) they can be sorted according to this
ordering by passing the list as an argument.
Write the one line code to sort our herbList using the variable Collections.
Collections.sort(herbList);
will sort the contents of herbList alphabetically. If we sort a list of numbers, they will be put into ascending numerical order.
This method is destructive.
Lists:-
Swapping
Two elements can be swapped by passing the list and the positions of the items concerned.
Write the one line code to exchange the third herbList element with the fifth element from the variable collections
Collections.swap(herbList, 2, 4);
remembering it is zero-based indexing so the first element is 0, second is 1… the above code will exchange the third element of herbList at index 2 with the fifth element at index 4.
If the method is called with either index out of range, an exception will be thrown.
This method is destructive.
Lists:-
Shuffling
The elements in a list can be put into random order by passing the list as an argument
Write a one line code to shuffle the cardList in the variable Collections
Collections.shuffle(cardList);
would put a deck of cards into a random sequence.
This method is destructive.