What is the difference between an abstract data type and a data structure? (Write 1-3 sentences.)
For this question, clearly state whether the following statement is true or false. Then, write one sentence to justify your answer. (Note: Your justification is the most important part of your answer.)
For loops are always O(N).
Marble
[8 pts]Consider the following class:
public class Marble {
private ArrayList<String> colors;
public Marble(String marbleColors) {
// Your code goes here
}
public boolean addColor(String newColor) {
// Your code goes here
}
public String toString() {
String ret = "Marble ( ";
for(String s: this.colors) {
ret += s + " ";
}
return ret + ")";
}
}
Also consider the following testcode:
/* The constructor takes a string
* of comma separated colors
*/
Marble m = new Marble("red,blue");
System.out.println(m);
/* Add green. Returns true because
* green is successfully added
*/
boolean res;
res = m.addColor("green");
System.out.println(res);
/* Add red. Returns false because
* red is already one of the colors
*/
res = m.addColor("red");
System.out.println(res);
System.out.println(m);
With a proper Marble
class, this code will output:
Marble ( red blue )
true
false
Marble ( red blue green )
Write the constructor Marble(String marbleColors)
for the Marble
class. You do not need to rewrite the class declaration or the method prototype, just the method’s code is fine. The code should function as demonstrated by the testcode.
addColor
Write the addColor
method of the Marble
class. You do not need to rewrite the class declaration or the method prototype, just the method’s code is fine.
The code should function as demonstrated by the testcode.
ConstantMarble
[6 pts]This problem builds on the previous problem. If your Marble
solution does not work, that is fine: It is still possible to receive full points on this problem.
A ConstantMarble
is-a Marble
, but it is one that cannot have its colors modified after it is created.
Consider the following testcode:
/* The constructor here functions the same
* as a standard Marble
*/
Marble cm = new ConstantMarble("red,blue");
System.out.println(cm);
/* Add green. Returns false because you
* cannot add a color to a ConstantMarble
*/
boolean res;
res = cm.addColor("green");
System.out.println(res);
System.out.println(cm);
With a proper Marble
class and ConstantMarble
class, this code will output:
ConstantMarble ( red blue )
false
ConstantMarble ( red blue )
Write the ConstantMarble
class. For full credit, you must properly make use of inheritance, including avoiding unnecessary code duplication.