Unit 10 Sets and Maps Flashcards

1
Q

Sets:-

Consider the following statement that declares and creates a new set of strings:

Set < String > herbSet = new HashSet < String > ( );

Answer the following questions:

(a) What is the purpose of < String > , which occurs twice in the above statement?
(b) Given an initial decision to use HashSet, why should the instance of HashSet be referenced by avariable of type Set?
(c) Given an initial decision for herbSet to be of type Set, why should the HashSet class be used?

A

(a) The first occurrence of in this statement is used in the declaration of the variable herbSet. It specifies that herbSet can only be used to reference a set whose element type is String. The second occurrence of is used with the HashSet constructor and the keyword new to create a set with the element type of String.
(b) It is good practice, where possible, to declare the variable in terms of an interface type (here Set), not the type of the implementing class (here HashSet). This promotes flexibility and hence maintainability.
(c) If we require a class that implements the Set interface and have no other information on which to base our choice, HashSet is a good general-purpose choice.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Sets:-

Set < String > herbSet = new HashSet < > ( );

This statement can not compile successfully unless we also tell the compiler where to find the definitions for both the Set interface and the HashSet class, so any class in which the statement above appears will have to import these definitions from the appropriate java package. The simplest approach is to import the whole package with the statement:
import java.\_\_\_\_\_\_
A

import java.util.*

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Sets:-

One of the simplest things you can do with a set is to test its size. This can be done using the message ______( ). As you might expect, the size of a newly created empty set is 0.

Our first example illustrates this:
Set < String > herbSet = new HashSet < > ( );

int size = herbSet.______( );

System.out.println(“The size of the newly created set is “ +size);
When executed, the above code prints the string “The size of the newly created set is 0” in the Display Pane.

A

size( )

thereforethe code should read:
Set < String > herbSet = new HashSet < >( );

int size =herbSet.size();

System.out.println(“The size of the newly created set is “ +size);

size( ) is a testing method which means it does not alter the set, just reports on it.

public int size()

Category testing

Returns the number of elements in the receiver.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Sets:-

We can add elements to a set, one at a time, with the message ______(), as demonstrated by the following code:

Set < String > herbSet = new HashSet < String > ( );

herbSet.______(“Parsley”);

herbSet.______(“Sage”);

herbSet.______(“Rosemary”);

System.out.println(“Size after adding elements: “ +herbSet.size( ));
Note we can only add elements that are type compatible with the declared element type of the variable herbSet.

A

add( )

Set < String > herbSet = new HashSet < String > ( );

herbSet.add(“Parsley”);

herbSet.add(“Sage”);

herbSet.add(“Rosemary”);

System.out.println(“Sizeafter addingelements: “ +herbSet.size( ));

public boolean add(ElementType obj)

Category adding

Adds the argument to the receiver, unless it is already there. Returns true if the argument was added, false if it was not.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Sets:-

Set < String > herbSet =new HashSet < > ( );

herbSet.add(“Parsley”);

herbSet.add(“Sage”);

herbSet.add(“Rosemary”);

herbSet.add(“Rosemary”);

herbSet.add(“Rosemary”);

System.out.println(“Size of herbSet: “ +herbSet.size( ));

what value will be returned?

A

A distinctive behaviour of sets is that the same element can not appear twice. If an attempt is made to add an element already present, the state of the set is left unaltered. The code sample demonstrates this.

Although add() is used five times, there are only three distinct elements involved and consequently the final size is 3 not 5.

The code displays:
Size of herbSet: 3

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Sets:-

isEmpty () to determine whether a set isEmpty of elements - what variable result value will the code assign:

Set < String > herbSet =new HashSet < String >( );

boolean result;

herbSet.add(“Parsley”);

herbSet.add(“Sage”);

herbSet.add(“Rosemary”);

result = herbSet.isEmpty();

What value is returned?

A

In the code, the variable result is assigned the value false.

isEmpty() is a testing method, same as size() and contains()

public boolean isEmpty()

Category testing

Returns true if the set is empty, otherwise false.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Sets:-

contains() to determine whether a set includes a particular element - what variable result value will the code assign:

Set < String > herbSet = new HashSet < >( );

herbSet.add(“Parsley”);

herbSet.add(“Sage”);

herbSet.add(“Rosemary”);

result =herbSet.contains(“Sage”);

A

In the code, the variable result is assigned the value true.

contains() is a testing method, same as size() and isEmpty()

public boolean contains(Object obj)

Category testing

Returns true if the argument is an element in the receiver, false if not.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Sets:

Diamond operators and Java versions:-

Which of the following code would compile using Java 7?

(a) Set < String > herbSet = new HashSet < String > ( );
(b) Set < String > herbSet =new HashSet < >( );>

A

both

from Java7 onward the right-hand-side diamond operators can be left empty as Java will automatically know it is the same element type as the left-hand-side

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Sets:

Diamond operators and Java versions:-

Which of the following code would compile using Java 6?

(a) Set < String > herbSet = new HashSet < String > ( );
(b) Set < String > herbSet = new HashSet < >( );

A

only (a)

it was only since Java version 7 onward you can leave the right-hand-side diamond operators empty

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Sets:-

Will this compile?

Set < String > herbSet = new HashSet ( );

A

yes

However, firstly, it is bad practice to omit the diamond operator altogether.

The code should generate a compiler warning about an unchecked or unsafe operation because it creates a collection without specifying a type of element that the collection will hold. This style of declaration was used before Java5.

Such warnings are suppressed in theOUWorkspace. For backward compatibility reasons, the designers of Java still allow these raw collections to be used, but the compiler for later versions of Java may warn you if you do so because these earlier collections did not provide the same level of type checking as the new ones do.
Secondly, it is important to note that a lot of existing code you may encounter elsewhere will have been written before Java 7, and will not use the diamond operator. Thus it helps to be able to read and write such code. Because of this, both approaches are in the module.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Sets:-

What is the message to remove an element from a set object to produce the message answer true if its argument was found and removed, and false if it was not found.

Set < String > herbSet = new HashSet < > ( );

herbSet.add(“Parsley”);

herbSet.add(“Sage”);

herbSet.add(“Rosemary”);

boolean removed =herbSet.______(“Parsley”);

if (removed)

{

OUDialog.alert(“Herb removed”);

}

else

{

OUDialog.alert(“Herb not found”);

}

A

remove( )

These message replies can be very useful. For example, if an element cannot be removed because it was not present, then for some applications it might be important to take some action such as warning the user, as illustrated by the code.

public boolean remove(Object obj)

Category removing

If the argument is an element in the receiver it is removed from the receiver and the method returns true. If the argument is not an element in the receiver, the receiver remains unchanged and the method returns false.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Sets:-

Will the following code compile?

Set < int > numSet = new HashSet < > ( );

A

The code is not legal so will not compile

When introduced to sets we have focused on sets of < String > , but you can create sets containing different element types in the same way. However, sets must hold references to objects; the element type can not be int or any other primitive data type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Sets:-

Due to Sets only allowing Reference data types, such as <string> we can not use <strong><int></int></strong>, we need to rely on a <strong>Wrapper Class</strong>. In this case, for int, the wrapper class name is \_\_\_\_\_\_.</string>

A

Integer

Luckily, for every primitive type, there is a corresponding class of objects we can use to ‘wrap’ values of that type.
Otherwrapper classes are Long, Float, Double, Short, Byte, Character, and Boolean.The corresponding primitive data types will be clear from the names, but note that char is spelled out in full as Character.

Wrapper classes are quite simple library classes that provide an object-oriented version of primitive types.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Sets:-

Wrap and UnWrap

create an instance of Integer, with the variable name wrappedNum to wrap the primitive value 7

A

Integer wrappedNum = new Integer (7);

using the Integer class constructor with the value you want to wrap as an argument.
You can extract (we also say ‘unwrap’) the primitive value again like this:

int unwrappedNum = wrappedNum.intValue();

using the intValue() method of the Integer class, which returns an int

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Sets:-

Wrapping

Integer wrappedNum = new Integer (7);

and unwrapping

int unwrappedNum = wrappedNum.intValue();

is fairly straightforward, but when we use numbers we generally want to do arithmetic with them.The arithmetic cannot in general be carried out on the Integer objects directly, so we have to unwrap the primitive values first, then do the calculation, and then wrap the answer back up again. This can involve a lot of programming overhead. However, in early versions of Java there was no other option.

Until Java 1.5 onwards, the wrapping is done for us automatically. This is called _______ and the unwrapping is called _______

A

auto-boxing and auto-unboxing

allowing us to write code such as:

  • Set < integer > myNumbers = new HashSet < integer > ( );*
  • myNumbers.add(7)*

the compiler will translate the second statement into bytecode that takes care of everything for us. It is as though primitive values can be added directly into the collection – although really, behindthe scenes, wrapper objects are being used.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Sets:-

Consider a set declared as follows:

Set< Integer > numSet = new HashSet < > ( );

We can add some primitive int values to this set as follows:

numSet.add(5);

numSet.add(6);

numSet.add(5);

The effect of evaluating these statements will be that the primitive values will be boxed as Integers automatically before they are added to the set.

What will the class of each element of numSet be after the above statements have been evaluated?

A

The class of each element of numSet will be Integer

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Sets:-

Using paper and pencil

/**

*Demonstrates the creation of a set of Integers and

*the subsequent adding and removing of elements.

*/

Set < Integer >numberSet = new HashSet < > ( );

int anInt = 4;

numberSet.add(anInt);

//try different integer values for anInt

numberSet.add(1);

numberSet.add(4);

numberSet.add(5);

numberSet.remove(6);

numberSet.remove(1);

Suppose the above example code is evaluated on three different occasions, each time using a different value of anInt as follows:
(1) anInt = 1;

(2) anInt = 6;
(3) anInt = 2;

For each case, describe the resulting state of numberSet.

A

After anInt = 1;

<1> | <1> | <1,4> | <1,4,5> | false | true <4,5>

the set contains Integer objects that wrap the int values 4 and 5. <4,5>

_____________________________
After anInt = 6;

<6>| <6,1> | <6,1,4> | <6,1,4,5> | true <1,4,5>| true <4,5>
the set contains Integer objects that wrap the int values 4 and 5. <4,5>

_____________________________
After anInt = 2;

<2> | <2,1> | <2,,4> | <2,1,4,5> | false | true <2,4,5>
the set contains Integer objects that wrap the int values 2, 4 and 5. <2,4,5>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Sets:-

Set < Integer >numSet = new HashSet< > ( );

numSet.add(12);

numSet.add(9);

numSet.add(88);

Write a for-each statement to print out the sum of the numbers

A

one such statement could be:

inttotal = 0;

for (Integer eachNum : numSet)

{

total =total +eachNum;

}

System.out.println (“Sum of all elements: “ +total);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Sets:-

If a for-each statement declares its local variable with the identifier each instead of eachNum, would there be a compilation error?

for (Integer each : numSet)

A

No, any valid identifier can be used for a for-each statement’s local variable. However, you might want to argue that calling the variable eachNum (or eachAccount, eachHerb or eachName) makes it easier for the human reader to understand what is happening.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Sets:- Given the code:

  • Set < Integer > numSet =new HashSet< >();*
  • numSet.add(12);*
  • numSet.add(9);*
  • numSet.add(88);*
  • inttotal = 0;*
  • for (Integer eachNum : numSet)*
  • {*
  • total =total +eachNum;*
  • }*
  • System.out.println (“Sum of all elements: “ +total);*
    (a) Why has the for-each statement’s local variable eachNum been declared to be of the Integer class, when the code prior tothe foreach statement has been adding values of the primitive type int to the set?
    (b) In a HashSet, can we predict with certainty in what order the elements will be iterated over?
A

(a) The variable numSet was declared as type Set, so eachNum was declared to match the element type. All the elements in the set are instances of the Integer class. However, auto-boxing allows you to use the type int for the variable numSet as well.
(b) No. The order is undefined and there is no way to predict it. see below from Java Docs

public class HashSet extends AbstractSet

implements Set, Cloneable, Serializable

This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Sets:-

Is it possible to use itertion (for-each loop) to remove elements or replace elements?

A

no, more advance techniques are needed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Sets:-

Just as with arrays, it is possible to iterate through a set using a hand-coded for loop instead of a for-each loop. However, for a set this is less straightforward. With an array we can simply use an int counter to represent the numerical index of each element in turn, and increment the index each time the loop is executed.

Why will this plan, which works for an array, not work for a set?

A

Remember, sets are dynamic, allow no dupliates, not indexed and generally unordered…

Sets have no index and so there is simply no way to access the elements of a set using an integer counter. You can however (just not in this modue) iterate over a set after obtaining an instance of an Iterator, using the set’s iterator() method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Sets:-

The following example code creates a set of strings with each element being the name of a herb. The last line of the code then prints the size of the set to the standard output.

Set < String >herbSet = new HashSet< >( );

herbSet.add(“camomile”);

herbSet.add(“rosemary”);

herbSet.add(“basil”);

herbSet.add(“thyme”);

herbSet.add(“mint”);

herbSet.add(“sage”);

herbSet.add(“lovage”);

herbSet.add(“parsley”);

herbSet.add(“chives”);

herbSet.add(“marjoram”);

System.out.println(herbSet.size());

What if, instead of printing out the size of the set, we wanted to print out the contents of the set, string-by-string?

Using the above code, create a modified version of the code as follows: Within the statement block of a for-each statement the code should printout to the Display Pane the name of each herb. You don’t need to write the code to add() the herbs just the for-each statement

A

for (String herb: herbSet)

{

System.out.println(herb);

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Sets:-

If we wanted to print out the herbSet alphabetically, how could you modify the code below:- hint: not much needs altering

Set < String > herbSet = new HashSet < > ( );

herbSet.add(“camomile”);

herbSet.add(“rosemary”);

herbSet.add(“basil”);

herbSet.add(“thyme”);

herbSet.add(“mint”);

herbSet.add(“sage”);

herbSet.add(“lovage”);

herbSet.add(“parsley”);

herbSet.add(“chives”);

herbSet.add(“marjoram”);

for (String herb: herbSet)

{

System.out.println(herb);

}

A

Set < String >herbSet = new HashSet< >( );

becomes

Set < String >herbSet = new TreeSet< >( );

Told you it wasn’t much!

The herbs will now automatically be in order. This begins to illustrate some of the power of the Java Collections Framework.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Maps:-

Maps are a collection with keys and values.

True or False:

key (what you find there) and value (the thing you look up)

A

False

rosehip 42

raspberry 32 & 76

mango and ginseng 18

This extract from a book index has entries consisting of a key (the thing you look up) and a value (what you find there).

For example, 42 is the value corresponding to the key ‘rosehip’. This way of structuring information is the motivation behind the collection known as a map.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

Maps:-

Why can’t we “Map” books by a Key being represented by the Books Title and the Value being represented by the books available format :

Key — Value

The Shining — Hardback, Paperback, Audio, EBook

How to become successful — Hardback, Paperback, Audio, EBook

Beginners Guide To Beer — Hardback, Paperback, EBook

My Saucy Sauces — EBook

A

The Value is legal as it is ok not to be unique. more than one author has a paperback and EBook.

The Key must be unique. There will be more than one book called “How to become Successful”

Consequently, merely knowing the book title and author of a book is not always enough to identify uniquely a specific edition. Hence, for the purpose of identifying book editions, book title and author alone would not make a sensible key.

A better way of uniquely identifying book editions is the International Standard Book Number ( ISBN ).

(Note though that the ISBN would be no good as a key for distinguishing your copy of the same edition from my copy of the same edition because they will both have the same ISBN. So what makes a good key depends on your purposes. It depends on exactly what you need to distinguish.)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Maps:-

For each of the following, say whether or not it makes an acceptable key. If you think it would, suggest what kind of value the key might be associated with.

(a) A staff ID number for employees in a company.
(b) The name of your Open University (OU) tutor amongst the body of OU tutors.
(c) Your OU student identifier amongst all OU students.

A

(a) This would normally be a unique key. Examples of appropriate values include an employment record or personnel file.
(b) This choice of key is not acceptable because it is possible that some OU tutors may have the same name. ( If tutor names were unique, a likely value for this key would be a tutorial group.)
(c) This is a unique key. The value might be, for example, marks for a given module or the student record.

In summary, when devising any scheme for keys for objects in some group, the vital consideration is that each key should be unique within the collection.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Maps:-

Assuming that the name is the key, which of the two following telephone directories is suitable for representing directly as a map? Give a reason for your answer.

((see image)

A

There is no problem with Directory A. Noggin the Nog and Queen Nooka are two keys with the same value, but this is perfectly allowable for maps.

Directory B can not be used directly as a map, since Pirate Jake’s name is not unique in this directory, and so names cannot act as unique keys for extension numbers.

We could get round this by changing the type of the values to be stored in the map from individual extension numbers into sets of extension numbers. Thus, Pirate Jake could still have two telephone numbers while everyone else had a single number, but now each key would have a single value, which is a set of numbers, even though the majority of sets just had one number in them. This approach is illustrated in the following table.

Name — Telephone number
Capt Pugwash — 6001

Tom the Cabin Boy — 5204

Pirate Jake — 0667, 0668

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

Maps:-

When creating a set we had to specify the type of the elements that would be stored in it. Before creating an instance of a map, it is necessary to specify two things:

the type of the keys and the type of the values to be stored.

Can these be different from each other?

A

Yes

For example, to keep track of customers’ bank accounts, you might use strings containing account numbers as keys and instances of Account as values. Or Integer ISBN numbers and String formats for library books.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

Maps:-

Map < String, Account > accounts = new HashMap < String, Account > ( );
or
Map < String, Account > accounts = new HashMap < > ( );

In the above statements, the declared type of the variable accounts is Map, while its implementing class is HashMap.

Explain why…

A

As we noted with Set, it is generally good practice to use a collection interface as the type of the variable. This promotes flexibility and maintainability. It was this choice that allowed us in Sets to change a HashSet to a TreeSet without changing the reference variable type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Maps:-

Declare an instance of HashMap whose keys are strings and whose values are accounts, and a variable accounts that can be used to reference that map.

A

Map < String, Account > accounts = new HashMap < String, Account > ( );

Just as with the declarations you saw for sets, it is helpful to save typing by using the diamond operator, as follows:

Map < String, Account> accounts = new HashMap < > ( );

32
Q

Maps:-

Using a general-purpose map interface, declare a Map with both KEYS and VALUES as String. The variable will be called Phonebook.

Once declared, print out the size of phonebook using System.out

A

Map < String, String > phonebook = new HashMap < String, String > ( );

int size = phonebook.size( );

System.out.println(“Size of newly created phonebook:” +size);

remember the first line could also have read :

Map < String, String > phonebook = new HashMap < > ( );

33
Q

Maps:-

Using a general-purpose map interface, declare a Map with both KEYS and VALUES as String. The variable will be called Phonebook. Once declared, add some entries to the newly created map and print out what the map size is after adding entries:-

Captain Pugwash, 6001

Tom the Cabin Boy, 5204

Pirate Jake, 0667

A

We use the message put() to add a key–value pair (also known as an entry or mapping) to a map. This is demonstrated below:

Map < String, String > phonebook = new HashMap < > ( );

phonebook. put(“Captain Pugwash”, “6001”);
phonebook. put(“Tom theCabin Boy”,”5204”);
phonebook. put(“Pirate Jake”,”0667”)

int size = phonebook.size( );

System.out.println(“Size after adding entries is: “+phonebook.size());

note: we used < String, String > pairs, so the numbers for the phone extension were placed in double quotes. You might have wondered why we have represented the telephone numbers as strings, not as integers. The reason is that telephone numbers can have leading zeros, whereas integers cannot. This is the same reason to use strings as account numbers

34
Q

Maps:-

(a) Create a map referenced by avariable poetMap. The keys of this map should be declared as Integer and the values as String.
(b) Your code example should then print to the Display Pane ‘The map is empty:’ followed by ‘true’ or ‘false’.

Whether the map is empty or not can be determined by sending the message isEmpty() to the map object.

(c) Your code should then add the following entries to poetMap, then printout ‘The size of the map is: ’ followed by the current size of the map.

Key — Value
205646 — “Dylan Thomas”

217887 — “Stevie Smith”

327886 — “Ted Hughes”

433457 — “Stevie Smith”

578799 — “Seamus Heaney”

A

Map < Integer, String > poetMap = new HashMap < Integer, String > ( );

System.out.println(“The map is empty:” +poetMap.isEmpty( ) );

poetMap.put (205646, “Dylan Thomas”);

poetMap.put(217887, “Stevie Smith”);

poetMap.put(327886, “Ted Hughes”);

poetMap.put(433457, “Stevie Smith”);

poetMap.put(578799, “Seamus Heaney”);

System.out.println (“The size of the map is: “ +poetMap.size( ) );

35
Q

Maps:-

Given the code:

Map < Integer, String > poetMap = new HashMap < Integer, String > ( );

System.out.println(“The map is empty:” +poetMap.isEmpty( ));

poetMap.put (205646, “Dylan Thomas”);

poetMap.put(217887, “Stevie Smith”);

poetMap.put(327886, “Ted Hughes”);

poetMap.put(433457, “Stevie Smith”);

poetMap.put(578799, “Seamus Heaney”);

System.out.println (“The size of the map is: “ +poetMap.size( ));

Write the line of code which would retrieve the String value of the key 433457 and assign it to a variable called poet.

A

String poet = poetMap.get (433457);

The above example is straight forward. But what happens if we try to retrieve a value from a map using get() with a key that does not exist in the map? For example:
String poet = poetMap.get (111111);
In this case, as poetMap does not contain an entry with the key 111111, the message get() returns null, which is then assigned to poet.

36
Q

Maps:-

What happens if we execute the following code which adds two entries, both with the same key?

poetMap.put (111111, “John Cooper Clarke”);

poetMap.put (111111, “WilliamWordsworth”);

A

the second put() message simply overwrites the value of the entry with the key 111111 with the new value “William Wordsworth”, and the value “John Cooper Clarke” then no longer exists in the map. This behaviour is by design: a key can be associated with one value only, and the last value associated with a key is the value that is stored. However, the put() message returns any previously stored value as its answer, so if you were to execute the two put() messages above in theOUWorkspace the output seen from the second put() message would be “John CooperClarke”.

37
Q

Maps:-

Map < String, String > phonebook = new HashMap < > ( );

phonebook. put ( “Captain Pugwash”, “6001” );
phonebook. put ( “Tom the Cabin Boy”, “5204” );
phonebook. put ( “Pirate Jake”, “0667” );

Write a line of code to remove the key-value pair “Pirate Jake” / “0667” from the map.

A

phonebook.remove(“Pirate Jake”);
This line of code will remove the key–value pair “Pirate Jake” / “0667” from the map.

The message also returns the value associated with the removed entry.

If you try to remove an entry from a map for which no matching key is present, the code will execute without any problem, as remove() deals with missing keys in the same way as the message get() – it simply returns null.

38
Q

Maps:-

Using the code below, extend the code by adding the following steps.

(a) Your code should print out ‘The value associated with the key 578779 is:’ followed by the associated value. This information should be obtained using a message from the protocol of Map.

Map < Integer, String > poetMap = new HashMap < > ( )

poetMap.put (205646, “Dylan Thomas”);

poetMap.put (217887, “Stevie Smith”);

poetMap.put (327886, “Ted Hughes”);

poetMap.put (433457, “Stevie Smith”);

poetMap.put (578799, “Seamus Heaney”);

A

System.out.println (“The value associated with key 578799 is: “ +poetMap.get(578799));

39
Q

Maps:-

Given the code below:

Write code to print out ‘The value associated with the key 123456 is:’ followed by the associated value. Also write down what you think would be the value returned when executed.

Map < Integer, String > poetMap = new HashMap < > ( )

poetMap.put (205646, “Dylan Thomas”);

poetMap.put (217887, “Stevie Smith”);

poetMap.put (327886, “Ted Hughes”);

poetMap.put (433457, “Stevie Smith”);

poetMap.put (578799, “Seamus Heaney”);

A

System.out.println ( “The value associated with key 123456 is: “ +poetMap.get (123456) );

null

40
Q

Maps:-

Given the code below:

Write code to add an entry with key 578779 and value “Brian Patten”.

Your code should then printout ‘The value for the key 578779 is:’ followed by the associated value.

Map < Integer, String > poetMap = new HashMap < > ( )

poetMap.put (205646, “Dylan Thomas”);

poetMap.put (217887, “StevieSmith”);

poetMap.put (327886, “Ted Hughes”);

poetMap.put (433457, “StevieSmith”);

poetMap.put (578799, “Seamus Heaney”);

A

poetMap.put (578799, “Brian Patten”);

System.out.println ( “The value associated with key 578799 is: “ +poetMap.get (578799) );

41
Q

Maps:-

Given the code below:-

write code to remove any entry whose key is 433457, and print out a message showing what value was found associated with this key. This information should be obtained using a message from the protocol of Map.

Map < Integer, String > poetMap = new HashMap < > ( )

poetMap.put (205646, “Dylan Thomas”);

poetMap.put (217887, “Stevie Smith”);

poetMap.put (327886, “Ted Hughes”);

poetMap.put (433457, “Stevie Smith”);

poetMap.put (578799, “Seamus Heaney”);

A

String value = poetMap.remove (433457);
System.out.println (value);

42
Q

Maps:-

Given the code below:- print out ‘The map contains an entry for key 217887:’ followed by the word ‘true’ or ‘false’. This information should be obtained using a message from the protocol of Map.

Your code should then print ‘The map contains an entry whose value is Ted Hughes:’ followed by the word ‘true’ or ‘false’. The required information should be obtained using a message from the protocol of Map.

Map < Integer, String > poetMap = new HashMap < > ( )

poetMap.put (205646, “Dylan Thomas”);

poetMap.put (217887, “Stevie Smith”);

poetMap.put (327886, “Ted Hughes”);

poetMap.put (433457, “Stevie Smith”);

poetMap.put (578799, “Seamus Heaney”);

A

System.out.println ( “The map contains an entry for key 217887: “ +poetMap.containsKey (217887) );

System.out.println ( “The map contains an entry whose value is Ted Hughes: “ +poetMap.containsValue (“Ted Hughes”) );

43
Q

Maps:-

What is the chief difference between sets and maps for the purpose of iteration?

A

In the case of a set, each element is a single object. In the case of a map, each element will be an entry; that is, a key–value pair.
For this reason, when iterating over a map, depending on what exactly is required for the purposes of the program, it may be necessary to extract both the key and value for each entry.

44
Q

Maps:-

Classes that implement the Map interface have two very useful messages keySet() and values() in their protocols. What is a key set?

A

A key set is simply a set of all the keys in a map. Below is an example creating a set of keys from a map

Map < String, String > dictionary = new HashMap < String, String > ( );

dictionary. put (“one”, “ichi”);
dictionary. put (“two”, “ni”);
dictionary. put (“three”,”san”);
dictionary. put (“four”, “shi”);

Set < String > dictionaryKeys = dictionary.keySet ( );

45
Q

Maps:-

using pen and paper…

Your code should create a map referenced by a variable ageMap, whose keys are strings and whose values are integers, and then add the following entries to ageMap:
Key–Value
“Jill” 33

“James” 45

“Louise” 57

“Peter” 26

“Sally” 51

Create an integer variable totalAge whose initial value is 0. Using the message keySet() get the set of the map’s keys. Then iterate over that set and for each key in the set look up the corresponding age in ageMap, and add it to the total age. When the iteration is complete, calculate the average age by dividing the total age by the size of the map (which corresponds to the number of entries). Print the average age to the Display Pane.

A

One solution is as follows:

Map < String, Integer > ageMap = new HashMap < String, Integer > ( );

ageMap.put (“Jill”, 33);

ageMap.put (“James”,45);

ageMap.put (“Louise”, 57);

ageMap.put (“Peter”,26);

ageMap.put (“Sally”,51);

int totalAge = 0;

for ( String eachName : ageMap.keySet ( ) )

{

totalAge = totalAge +ageMap.get (eachName);

}

int averageAge = totalAge /ageMap.size ( );

System.out.println (“The average age is: “ +averageAge);

___________

Sending the message keySet () to a map does not in anyway disturb the keys or values in the original map. However, although the set of keys is a new collection, it is important to note that the elements in the set are the actual keys from the original map, not copies. Consequently, should you remove a key from the set, the corresponding key–value pair will be removed from the map. The reverse is also true: removing a key–value pair from the map will remove the key from the set. The keyset is actually just a different view of the same keys.

46
Q

Maps:-

Removing a value from the collection will result in the corresponding key–value pair being removed from the map. Answer the following:

(a) The message keySet() when sent to a map will collect all the map’s keys into a set. The nature of sets will demand that only unique elements are stored in the set – any duplicate keys would be lost. Is there a risk of losing duplicate keys?
(b) Whenever you send the message keySet() to a map, a new set is returned. However, the keys held in this new set are not copies of the keys in the map, they are the actual keys. If you subsequently removed a key from the set of keys what would happen to the key in the original map?

A

(a) There is no such possible danger. The keys in a map must be unique in the first place – no duplicate keys are allowed.
(b) The key and its corresponding value would be removed from the original map.

47
Q

(a) What is the main difference between maps and sets?
(b) A collection is needed in an OU system to store student identifiers and associate them with the current total of OU credits each student has studied. Would a map be an appropriate collection interface for this task? Give a reason for your answer.

A

(a) The elements of a set are single objects whereas the elements of a map are key–value pairs.
(b) Student identifiers are unique and so make good keys. Total credits make legitimate values. So a map would be a good collection interface for this task.

48
Q

Maps:-

Which of the following statements are true and which are false? If you think a statement is false, give a reason.

(a) The message put( ) always creates a new entry in a map.
(b) Each entry in a map has a key and one or more values.
(c) Duplicate keys are allowed in a map.
(d) The message get( ) always returns the value of some entry within a map that has a key that matches the message’s argument.

A

(a) False. It may update an existing entry.
(b) False. An entry has only one value. Although you might use a class such as HashSet as the value type (which would indirectly allow you to store multiple values for a given key), the value associated with each key would still be a single reference to its particular set.
(c) False. Keys are unique in a map.
(d) False. The message get( ) returns the value of an entry if the map contains a key matching the message’s argument, otherwise the message returns null.

49
Q

Maps:-

Name a method in SortedSet that is not in Set.

A

Answer
Two good answers are first( ) and last( ). Other answers are possible.

50
Q

Maps:-
Do all of the classes in the Collections Framework implement the Collection interface?

A

Answer
Not all of the collection classes implement the Collection interface. Classes such as HashMap and TreeMap implement the Map interface. The Map interface is not a sub interface of the Collection interface, as can be seen in Figure3. The separateness of keys and values in any map keeps maps slightly apart from the other collections. For example, the message add( ),which is part of the Collection interface but not in the protocol of Map, would need to be dealt with rather differently in the case of a map. Despite this, we say that maps are part of the Collections Framework, since the framework was designed to cover not just the Collection interface but also the Map interface.

51
Q

Maps:-
Name any three methods in the Set interface and any three methods in the Map interface. At least two should be common to both interfaces.

A

Answer
Many correct answers are possible. isEmpty( ) and size( ) appear in both the Set and Map interfaces. The protocol for Set includes add( ), remove( ), contains( ) and many others. The protocol for Map includes get( ), put( ), removeKey( ), containsKey( ), containsValue( ) and many others

52
Q

Maps:-

We have not yet said anything about the interfaces List and Queue, but you can be sure that any abstract methods declared in Collection must be inherited by the interfaces Set, List and Queue. Why can we be sure of this?

A

Answer
We can be sure of this because, as Figure 3 shows, Set, List and Queue are sub interfaces of Collection.

53
Q

Collection Framework:-

Place HashMap, HashSet, TreeMap, TreeSet, LinkedList and ArrayList into the uncompleted figure

A

It doesn’t matter which way Hash and Tree has been entered as long as Maps are under AbstractMap and Sets are under AbstrractSet. The LinkedList is under the AbstractSequentialList whilst the ArrayList is a subclass of AbstractList

54
Q

Collection Framework:-

Set < String > herbSet = new HashSet < String > ( );

herbSet.add(“camomile”);

herbSet.add(“rosemary”);

herbSet.add(“basil”);

herbSet.add(“thyme”);

herbSet.add(“mint”);

herbSet.add(“sage”);

herbSet.add(“lovage”);

herbSet.add(“parsley”);

herbSet.add(“chives”);

herbSet.add(“marjoram”);

(a) Write a modified version of this code in which herbSet, the variable to reference an instance of TreeSet, is declared to be of type SortedSet. Then within a statement block write a for-each statement so the code prints out to the Display Pane the name of each herb.

At the end of your code you should print out the first and last entries of the sorted set by using appropriate SortedList protocol.

(b) Would your code compile if herbSet, the instance of TreeSet, had remained declared as a Set? Give a reason for your answer.

A

SortedSet < String > herbSet = new TreeSet < String > ( );

herbSet.add (“camomile”);

herbSet.add (“rosemary”);

herbSet.add (“basil”);

herbSet.add (“thyme”);

herbSet.add (“mint”);

herbSet.add (“sage”);

herbSet.add (“lovage”);

herbSet.add (“parsley”);

herbSet.add (“chives”);

herbSet.add (“marjoram”);

for (String herb: herbSet)

{

System.out.println(herb);

}
System.out.println ( “First herb is “ + herbSet.first ( )); System.out.println ( “Last herb is “ +herbSet.last ( ));

Just changing the type of the herbSet variable from Set to SortedSet enabled you to send the messages first( ) and last( ) to the set referenced by herbSet. As herbSet references an instance of TreeSet it should be clear to you that the TreeSet class must implement the SortedSet interface. Even though the TreeSet class implements the first( ) and last( ) methods and herbSet references an instance of TreeSet, our example code would not compile if the variable herbSet was declared to be of type Set, as first( ) and last( ) are not in the protocol of Set.

55
Q

Are arrays part of the Collections Framework?

A

NO

Arrays pre-date the Collections Framework and do not implement any of its interfaces. Consequently they are not considered to be part of the Collections Framework.

This historical accident explains much that would otherwise be mysterious about collections. For example, this explains (in part) why the notation for declaring arrays (square brackets after the component type) is so different from that of sets and maps < angle brackets around the element type >.

56
Q

Sets:-

given group1 and group2. If this figure show Intersection, and the protocol to get the intersection would be:-

group1.retainAll(group2);

write down the code to

(a) produce the “union” of group1 and group2
(b) produce the “difference” of group1 and group2

A

(a) group1.addAll(group2)
(b) group1.removeAll(group2)

57
Q

Sets:-

Given

Set < String > collection1 = new HashSet < > ();

Set < String > collection2 = new HashSet < > ();

So we don’t destroy the original collection1 when removing, adding or retaining, we can create a copy of collection1 called collection3. Write down the code to create this copy.

A

Set < String> collection3 = new HashSet < > (set1);

58
Q

Sets:-

addAll, removeAll and retainAll are destructive or non destructive operations?

A

Operations that alter the contents of the receiver are referred to as destructive operations, whereas those that do not are referred to as non destructive operations.

addAll, removeAll and retainAll are destructive

this is why we create a copy of the set before using such operations with the signature HashSet (Collection)

59
Q

Sets:-

1 Create two empty sets of strings referenced by the variables set1 and set2.

2 Using appropriate messages, initialise set1 so that it contains the elements “a”, “b”, “c”, “d” and initialise set2 so that it contains “f”, “c”, “g”, “a”

3 Alter the contents of set1 to the intersection of the two sets (that is, a set containing only the elements the two sets have in common).

4 Print out the contents of set1.

A

One possible solution is as follows:

Set < String > set1 = new HashSet < String > ( );

Set < String > set2 = new HashSet < String > ( );

set1. add(“a”);
set1. add(“b”);
set1. add(“c”);
set1. add(“d”);
set2. add(“f”);
set2. add(“c”);
set2. add(“g”);
set2. add(“a”);
set1. retainAll(set2);

System.out.println ( “The intersection is: “ );

for (String element : set1)

{

System.out.println (element);

}

60
Q

Dating Agency:-

Complete a simple instance method that uses a dialogbox to collect some strings representing client’s interests, collects them in a set, and then prints them out.

Write your method based on the incomplete code shown below:

import java.util.*;

import java.ou.*;

/**

*Creates a set referenced by the variable interestsSet

*and then repeatedly displays a dialog box

*(until cancel is pressed) in order to gather

*a client’s interests and add them to interestsSet.

*Finally the method returns interestsSet.

*/

public Set<string> gatherInterests (String client)</string>

{

//(a) Replace these comments with the code to create a

//new empty instance of HashSet < String > and

//assign it to a variable called interestsSet

//declared as type Set < String >.

String dialogString = “Please input an interest for “ +client +”. PressCancel to end.”;

String input = OUDialog.request(dialogString);

while (input != null)

{

//(b) Replace these comments with the code to add

//input to the set interestsSet.

input = OUDialog.request(dialogString);

}

return interestsSet;

}

A

(a) Set < String> interestsSet = new HashSet < > ( );
(b) interestsSet.add(input);

To test your method in theOUWorkspace you would need to write code similar to the following:

DatingAgency da = new DatingAgency();

da.gatherInterests(“Sue”);

61
Q

Dating Agency:-

create a second method for the class DatingAgency with the following header:
public run (String clientA, String clientB)

We expect this method to receive the names of two clients as arguments; that is, the names of two people who are using the dating agency.

This method should send the message gatherInterests() to this twice, first to collect interests for clientA and then for clientB. The results should be stored in local variables of type Set < String > called interestsA and interestsB, respectively.

To assist with testing your code, your method should then iterate through each set, printing out the interests to the Display Pane. Before displaying the contents of each set your code should first output a line that reads ‘Interests for client ’, followed by the name of the client.

___________________________________

import java.util.*;

import ou.*;

public class DatingAgency

{

public Set < String > gatherInterests(String client)

{

Set < String > interestsSet = new HashSet < > ();

String dialogString = “Please input an interest for “ +client +”. Press Cancel to end.”;

String input = OUDialog.request(dialogString);

while (input != null)

{

interestsSet.add(input);

input = OUDialog.request(dialogString);

}

return interestsSet;

}

}

A

Here is one possible solution:

/**

*Prints the interests of a pair of clients whose names

*are represented by the arguments.

*/

public void run (String clientA, String clientB)

{

Set < String > interestsA = this.gatherInterests(clientA);

Set < String > interestsB = this.gatherInterests(clientB);

System.out.println (“Interests for client “ +clientA);

for (String interest :interestsA)

{

System.out.println(interest);

}
System.out.println (“Interests for client “ +clientB);

for (String interest :interestsB)

{

System.out.println(interest);

}

}

You can test this method using code similar to the following:

DatingAgency da = new DatingAgency( );

da.run (“Sue”, “Bob”);

62
Q

Dating Agency:0

Modify the method run() so that once it has printed out the interests of both clients it creates a new set referenced by the variable declared as Set < String > common Interests, which is a copy of the set referenced by interestsA.The set referenced by commonInterests should then be altered to form the intersection with the set referenced by interestsB. If you need a refresher on this, you may find it useful to look back at Subsection 5.1 on bulk operations or at Activity 11.
Then add code to print ‘The common interests are’, followed by all the common interests.

/**

*Finds and prints the common interests of

*a pair of clients.

*/

public void run (String clientA, StringclientB)

{

Set < String > interestsA = this.gatherInterests (clientA);

Set<string> interestsB = this.gatherInterests (clientB);</string>

System.out.println (“Interests for client “ +clientA);

for (String interest : interestsA)

{

System.out.println (interest);

}
System.out.println (“Interests for client “ +clientB);

for (String interest : interestsB)

{

System.out.println (interest);

}

// insert your code here to create a copy of Set interestsA called commonInterests and then this set should contain only the common Interests from interestsA and B. Now print “The common interests are:” followed by all the common interests

A

Set < String > commonInterests = new HashSet < > (interestsA);

commonInterests.retainAll(interestsB);

System.out.println (“The common interests are: “);

for (String interest : commonInterests)

{

System.out.println(interest);

}

63
Q

Dating Agency - Maps < String, Set < String > > :-

The central idea is to use each client name as a key in a map. The value associated with each key will be a set of strings containing that client’s interests.

/**

*Stores and retrieves data about client names and

*interests.

*/

public void datingDemo( )

{

Map < String, Set < String > > clientMap = new HashMap < > ( );

Set < String > interests = new HashSet < > ( );

interests. add(“Food”);
interests. add(“Wine”);
interests. add(“Tandems”);

clientMap.put(“Hal”, interests);

interests = new HashSet < > ( );

interests. add(“Food”);
interests. add(“Walking”);
interests. add(“Welding”);

clientMap.put(“Gemma”, interests);

interests = new HashSet < > ( );

interests. add(“Food”);
interests. add(“Cinema”);
interests. add(“Wine”);

clientMap.put(“Caroline”, interests);
interests =clientMap.get(“Xander”);

System.out.println(“Xanders interests are “ +interests);

if ( (clientMap.remove(“Xander”) ) = = null)

{

OUDialog.alert(“Xander not found”);

}
for (String eachClient : clientMap.keySet( ))

{

interests = clientMap.get(eachClient);

System.out.println(eachClient +” is interested in: “ +interests);

}

}

Examine the above code of the method and answer the following questions:
(a) Why was it necessary to repeat the following statement:
interests = new HashSet < > ( );

after putting an entry into the map?

(b) The Set interface contains a method clear( ) that removes all of the elements from a set. Why can we not just use clear( ), instead of creating a new HashMap instance each time?

A

(a) Because otherwise there would only ever be one set and each time we added an entry into the map it would be this same set that got used. At the end all the clients would be associated with exactly the same HashSet object, and all the interests that had been added would have been inserted into this one set. The result would be that every client would appear to have an identical set of interests containing the pooled interests of all the clients.
(b) This would have a similar effect to the one described in item(a), except that the one and only set involved would have been cleared for each client. Consequently, at the end all that would be retained would be the interests of the final client, and the set containing these would be entered against the name of every single client.

64
Q

Dating Agency - Maps :-

The method matchesDemo() focuses on a specific client (“Hal”). This method uses the techniques for finding set intersections in order to check which of Hal’s interests match those of the other clients. This activity revisits an important technique for working with maps, namely working with the message keySet(). The simplest way of iterating over a map is to obtain a set of keys, and then iterate over them, using each key to access the corresponding value from the map as you go.

Set < String > halsInterests = clientMap.get(“Hal”);

String outputString;

Set < String > eachClientInterests;

Set < String > intersection;

for (String eachClient : clientMap.keySet( ))

{

eachClientInterests = clientMap.get(eachClient);

intersection= new HashSet < > (halsInterests);

intersection.retainAll(eachClientInterests);

outputString = “Hal and “ +eachClient +” have common interests: “ +intersection;

System.out.println(outputString);

}

why is intersection reinitialised each time with a fresh set containing Hal’s interests?

A

The set containing Hal’s interests is recreated as a fresh set with the same contents before calculating common interests because the set message retainAll( ) used to calculate set intersection is destructive; it changes the contents of the receiver. This would disturb subsequent calculations of common interests.

65
Q

The method as it stands matchesDemo() reports that Hal and Hal have common interests: “Wine”, “Food” and “Tandems”. This is rather silly because Hal should be compared only with everyone other than himself. Create a modified version of the method below to ensure that we do not compare Hal’s interests with Hal’s interests.

__________________________

Set < String > halsInterests = clientMap.get(“Hal”);

String outputString;

Set < String > eachClientInterests;

Set < String > intersection;

for (String eachClient : clientMap.keySet( ))

{

eachClientInterests = clientMap.get(eachClient);

intersection= new HashSet < > (halsInterests);

intersection.retainAll(eachClientInterests);

outputString = “Hal and “ +eachClient +” have common interests: “ +intersection;

System.out.println(outputString);

}

A

One solution is to iterate over map if not Hal:-

for (String eachClient : clientMap.keySet( ))

{

if (!eachClient.equals(“Hal”))

{

eachClientInterests = clientMap.get(eachClient);

intersection =new HashSet<>(halsInterests);

intersection.retainAll(eachClientInterests);

outputString =”Hal and”+eachClient +”have common interests: “ +intersection;

System.out.println (outputString);

}

}

__________________

The other way would be, before interation, create a set for each clients interests excluding Hal.

Map < String, Set < String > > mapWithoutHal = new HashMap < > (clientMap);

mapWithoutHal.remove(“Hal”);

for (String eachClient : mapWithoutHal.keySet( ))

{

eachClientInterests = clientMap.get(eachClient);

intersection = new HashSet < > (halsInterests);

intersection.retainAll(eachClientInterests);

outputString = “Hal and “ +eachClient +” have common interests: “ +intersection;

System.out.println(outputString);

}

66
Q

True or False

Different kinds of collection can be distinguished according to the following properties:

(a) fixed size versus dynamically resizable
(b) ordered versus unordered
(c) indexed versus unindexed
(d) whether duplicates are allowed or not.

A

all true

67
Q

The element type of collections doesn’t generally need to be declared.

A

False

68
Q

Array, Set or Map? - One answer can be used to answer all the sentences correctly:-

_____ are dynamically sized.

No element in a _____ can be duplicated.

A ____ is not indexed but some kinds of ____ are ordered.

A ____ is a collection of single objects not key–value pairs

A

Set

69
Q

Sets:-

HashSet and TreeSet are classes that are both implementations of the Set interface. Instances of ____Set are ordered; instances of ____Set are not.

A

TreeSet are ordered

HashSet are not

70
Q

Collections Framework:-

True or false?

The for-each loop (also known as the enhanced for loop)can be used to iterate over any collection?

A

True

71
Q

Maps:-

Maps have key–value pairs, also known as entries, as their elements. Is the same key allowed more than once in a map? Can the same value occur any number of times?

A

Maps hold unique keys but can contain the same value any number of times (eg., key “Student ID” and value grades - two different students can have the same value grade (“03756”, “A”) and (“03893”, “A”)

72
Q

(a) The protocol defined by the _____ interface includes size(), isEmpty(), containsKey(), containsValue(), put(), get() and remove()
(b) The protocol defined by the _____ interface includes size(), isEmpty(), contains(), add() and remove().

All these operations can be divided into the informal categories of testing, adding and removing.

A

(a) Map
(b) Set

73
Q

Maps:-

If the same key is put into a map twice with different values:-

(a) A run-time error will occur.
(b) The second value will overwrite the first.
(c) the second value will not be added.

A

(b) If the same key is put into a map twice with different values, the second value will overwrite the first.

74
Q

Maps:-

If get () or remove () are used with a key that is not present in the map, does an error message occur?

A

No, If get() or remove() are used with a key that is not present in the map, null is returned.

75
Q

Collections Framework:-

True or False?

The Collections Framework unifies the collection classes. It contains Three root interfaces, Arrays, Collection and Map. Set is a subinterface of Collection.

A

False

The Collections Framework unifies the collection classes. It contains two root interfaces, Collection and Map. Set is a subinterface of Collection.

Arrays are not part of the Collections Framework, as they do not implement either the Collection or Map interfaces.

76
Q

Sets:-

The bulk methods retainAll( ), addAll( ) and removeAll( ) correspond to the set operations known as:-

(a) intersection, union and difference
(b) union, difference and intersection
(c) different, union and intersection

__________________

These methods are ___________ as they alter the original set – so it is normally best to work with a copy. The method containsAll() is non-destructive.

A

(a) intersection (retainAll), union (addAll) and difference (removeAll)

and

These methods are destructive