• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

about generics

 
Preethi Dev
Ranch Hand
Posts: 265
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got it from
http://www.cafe4java.com/mockexams/scjp/mock4/q2.php

import java.util.*;
public class TestLaptop {
public static void main (String args[]) {
ArrayList list = new ArrayList();
list.add (new Laptop ("ToshibaA10", 4560.99));
list.add (new Laptop ("DellNU6", 8213.99));
list.add (new Laptop ("IBM", 1298.99));
Collections.sort(list);
System.out.println (list);
}
}

Which line of code, when replaced with '// INSERT CODE HERE' , will enable the class TestLaptop to print out the sorted collection of class 'Laptop'
// INSERT CODE HERE
String model;
double price;
Laptop(String model, double price) {
this.model = model;
this.price = price;
}
public String getModel() {
return model;
}
public int compareTo(Laptop otherLaptop) {
double otherLaptopPrice = otherLaptop.getPrice();
if (price < otherLaptopPrice) return -1;
else if (price > otherLaptopPrice) return 1;
else return 0;
}
public double getPrice() {
return price;
}
public String toString() {
return "\n" + model + " " + price;
}
}


A) class Laptop implements Comparable <Laptop> {
B) class Laptop implements Comparable {
C) class Laptop implements Comparator {
D) class Laptop implements Comparator <Laptop>{
E) None of the above

Answer is: A

Explanation :
Option B is incorrect because its usage will generate the following compilation error message:

Laptop is not abstract and does not override abstract method compareTo(java.lang.Object) in java.lang.Comparable class Laptop implements Comparable {

I thought the answer would be B.

Please anyone explain me this....
 
ramesh maredu
Ranch Hand
Posts: 210
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if you use
class Laptop implements Comparable then compareTo method syntax should be

public int compareTo(Object o)

if you use generic version like Comparable<Car> then method syntax would be



public int compareTo(Car c)
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic