• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

about generics

 
Ranch Hand
Posts: 265
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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....
 
Ranch Hand
Posts: 210
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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)
 
And inside of my fortune cookie was this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic