Win a copy of Rust Web Development this week in the Other Languages forum!
  • 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:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

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?
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic