Answers to the questions appear in blue text.
Commentary on the answer appears in red text.
public static void modify(Bag<String> bag) {
Bag<String> newBag;
while (!bag.isEmpty()) {
String s = bag.remove();
if (!newBag.contains(s)) {
newBag.add(s);
}
}
while (!newBag.isEmpty()) {
bag.add(newBag.remove());
}
}
Suppose myBag contains "A", "B", "C", "D", "A", "E", and "D".
What does myBag contain
after modify(myBag) has been called?
"A", "B", "C", "D" and "E"
bag
and puts each element into newBag
unless newBag already contains it.
Thus only one copy of each element gets into newBag.
The second loop empties newBag
back into bag,
leaving it with no duplicates.
Define the interface. (No comments necessary!)
public interface Unknown<T> {
public T get();
public void set(T newValue);
public boolean exists();
}
public
but not abstract
(even tho' they are both by default).
Show the contents of the array after
0 1 2 3 4 5 6 7 8 9 "Anita" "Bill" "Chantal" "Djeri" "Eli" "Frank" "Gordon" / / /
remove("Bill") has been executed.
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
| "Anita" | "Gordon" | "Chantal" | "Djeri" | "Eli" | "Frank" | / | / | / | / |
count method for the LinksBag class:
public class LinksBag<T> implements Bag<T> {
private class Node {
private Node next;
private T data;
}
private Node first;
}
The method counts how many times a given entry appears in the LinksBag object.
Do not use either toArray method,
nor any method that need to be imported,
and do not modify the contents of the bag in any way.
Note that this class does not have a numInBag field.
@Override
public int count(T item) {
int count = 0;
Node cur = first;
while (cur != null) {
if (Objects.equals(item, cur.data) {
++count;
}
cur = cur.next;
}
return count;
}
That works, but it's better programming practice to use the chain structure itself to control looping along the chain.
cur.next = first;
has been executed by putting X(s) thru old arrow(s) and adding new arrow(s).
obj,
and we want to check to see if it holds a Circle object,
the way to do that is
e
setColor and getColor do as their names imply?
Car myCar = new Car("Blue");
Car disCar = myCar;
Car stevesCar = new Car("Green");
disCar.setColor("Red");
myCar.setColor("Yellow");
System.out.print(disCar.getColor());
d
myCar and disCar
refer to the same Car object.
Its colour is blue at first,
then red,
and finally yellow.
e
c
b
a