• 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

Collections

 
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
what is the final output of the following code.
explain how it happens?


import java.util.*;
class Person implements Comparable{
String name;
int age;
Person(String s,int i){
name =s; age = i;
}
public int compareTo(Person p){
return this.name.compareTo(p.name);
}

public int compareTo(Object o) {
}
}
class A{
public static void main(String ar[]){
ArrayList<String> a = new ArrayList<String>();
a.add(new Person("mike"));
a.add(new Person("gayani"));
a.add(new Person("tharaka"));
a.add(new Person("sandra"));
Collections.sort(a);
System.out.println(a);
}
}
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
"Hassel,"

Please check your private messages by clicking on My Profile. Thanks!
 
marc weber
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Hassel:
what is the final output of the following code.
explain how it happens? ...


This will not even compile. First, the Person class does not have a constructor that takes a single String as an argument. Second, the compareTo(Object o) method is declared to return an int, but has no implementation. And third, the ArrayList takes Strings, so trying to add instances of Person will not work.

Supposing you added the constructor, provided (proper) implementation for the compareTo method, and changed the ArrayList type to Person, then the code will compile, but... The output won't tell you much, because the Person class has not overridden Object's toString method, so you will only see "cryptic" representations of instances.

Where did this code come from?
 
reply
    Bookmark Topic Watch Topic
  • New Topic