Andhra University 2007 B.E Computer Science s - Question Paper
Wednesday, 01 May 2013 05:50Web
Page 3 of 3
int day; // Day number in range one to 31.
int year; // Year number.
Date(int m, int d, int y) { // Convenience constructor.
month = m;
day = d;
year = y;
}
public int compareTo( Date otherDate ) {
// Returns 1, 0, or -1 if this date is greater than, equal to,
// or less than otherDate, respectively.
if (year < otherDate.year)
return -1;
else if (year > otherDate.year)
return 1;
else { // Years are equal; compare months.
if (month < otherDate.month)
return -1;
else if (month > otherDate.month)
return 1;
else { // Years and months are equal; compare days.
if (day < otherDate.day)
return -1;
else if (day > otherDate.day)
return 1;
else
return 0;
}
}
}
}
ques. 10:
Suppose that syllabus is a variable of kind TreeMap
Answer:
I will provide 2 solutions. 1 of them simply looks up every date in December, 2006 in the map and prints the corresponding value, if there is one. The other iterates though a submap that contains all the entries for dates in that month.
A solution using the map's get() method:
for (int day = 1; day <= 31; day++) {
// Get the info for 1 day in December, 2006
Date date = new Date(12,day,2006); // The key.
String info = syllabus.get(date); // Get the value for that key.
// (Can be null if there is no
// entry in the map for this date.)
if (info != null)
System.out.println("December " + day + ": " + info);
}
A solution using a submap (harder, but more efficient):
Date startDate = new Date(12,1,2006); // Starting date for submap.
Date endDate = new Date(1,1,2007); // Ending date for submap.
// (Remember that the end date
// is not included.)
Map
for ( Map.Entry
Date date = entry.getKey();
String info = entry.getValue();
System.out.println("December " + data.day + ": " + info);
}
ques. 11:
Write a generic class Stack
Answer:
public class Stack
ArrayList
public void push( T newItem ) {
stack.add(newItem);
}
public T pop() {
int top = stack.size() - 1; // location of top item
return stack.remove(top); // remove and return top item
}
public boolean isEmpty() {
return stack.size() == 0;
}
}
ques. 12:
Write a generic method, using a generic kind parameter
Answer:
Since the method operates on ArrayLists, it can use indexed access with the get(i) and set(i,item) methods. These operations are efficient for array lists. I also provide a 2nd version of the method that uses a list iterator and is efficient for any kind of list.
public static
if (oldItem == null) {
for (int i = 0; i < list.size(); i++) {
if ( null == list.get(i) )
list.set( i, newItem );
}
}
else {
for (int i = 0; i < list.size(); i++) {
if ( oldItem.equals(list.get(i)) )
list.set( i, newItem );
}
}
}
public static
ListIterator
while (iter.hasNext()) {
T listItem = iter.next();
if ( oldItem == null ) {
if ( listItem == null )
iter.set(oldItem);
}
else {
if ( oldItem.equals(listItem) )
iter.set(oldItem);
}
}
}
Earning: Approval pending. |