Reference no: EM132430772
Problem: The following code segment will be used for questions 6-10. The code in the class Book is complete, and ExamIITest contains only a partially completed main method (3 points each):
public class Book implements Comparable<Book> {
String title;
Map<Integer,String> pages;
public Book(String title) {
this.title = title;
this.pages = new TreeMap<Integer,String>();
}
public String getTitle() {
return this.title;
}
public int getNumPages() {
return this.pages.size();
}
public void addPage(int pNum, String page) {
this.pages.put(pNum,page);
}
public int compareTo(Book other) {
int cmp = 0;
if (this.getNumPages() < other.getNumPages()) {
cmp = -1;
}
else if (this.getNumPages () > other.getNumPages()) {
cmp = 1;
}
return cmp;
}
}
public class ExamIITest {
public static void main(String[] args) {
Book myFoo1 = new Book("Harry Potter");
Book myFoo2 = new Book("Lord of the Rings");
Book myFoo3 = new Book("1984");
myFoo1.addPage(1,"Hello"); myFoo1.addPage(2,"World");
myFoo1.addPage(3,"Goodbye"); myFoo2.addPage(1,"Frodo");
myFoo2.addPage(1,"Baggins"); myFoo3.addPage(1,"Big");
myFoo3.addPage(2,"Brother");
int cmp = myFoo1.compareTo(myFoo2);
System.out.println(cmp); (1)
PriorityQueue<Book> q = new PriorityQueue<Book>();
q.add(myFoo1);
q.add(myFoo2);
q.add(myFoo3);
Book b = q.remove();
System.out.println(b.getTitle()); (2)
}
}
1. In the code above, the method getTitle() is an example of (Mark ALL that apply):
a. An accessor method
b. A mutator method
c. A static method
d. A constructor method
e. None of the above
2. In the code above, what is the value held by the variable cmp when the statement marked with line (1) in the main method is reached?
a. 1
b. 0
c. -1
d. You cannot tell from the code provided
3. In the code above, what is the state of the variable named pages contained by the object myFoo1 hold when the statement marked with line (1) is reached?
4. In the code above, what is the state of the variable named pages contained by the object myFoo2 hold when the statement marked with line (1) is reached?
5. In the code above, what will be printed by the line of code when the statement marked with line (2) is reached?