• 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
  • Ron McLeod
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Rob Spoor
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Carey Brown
Bartenders:

comparator

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am not getting the desired output from the following code
I want to get the Strings to be sorted by last name and here I have overloaded comparator but its not comparing last names
kindly help me . moreover while execution it throws java.lang.nullpointerexception.The code is
import java.util.*;
class TComp implements Comparator{
public int compare(Object a, Object b){
int i, j, k;
String aStr, bStr;
aStr = (String) a;
bStr = (String)b;
i = aStr.lastIndexOf(' ');
j = bStr.lastIndexOf(' ');
k=aStr.substring(i).compareTo(bStr.substring(j));
if(k==0)
return aStr.compareTo(bStr);
else
return k;
}
}
public class TreeMapDemo2{
public static void main(String args[]){
TreeMap tm = new TreeMap();
tm.put("Sunil Bmar", new Double(3000));
tm.put("Dinesh Amar", new Double(100000));
tm.put("Ravi Chandwani",new Double(2000));
tm.put("Amit Kumar",new Double(30000));
tm.put("Bhushan Vasvani",new Double(5000));
tm.put("Kishan Ratnani",new Double(4000));
Set set = tm.entrySet();
Iterator i = set.iterator();
while(i.hasNext()){
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey()+ ": " );
System.out.println(me.getValue());
}
System.out.println();
double balance = ((Double)tm.get("Sunil kumar")).doubleValue();
tm.put("Sunil kumar",new Double(balance + 1000));
System.out.println("Sunil kumar's new balance : "+tm.get("Sunil kumar"));
}
}
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
<PRE>
i = aStr.lastIndexOf(' ');
j = bStr.lastIndexOf(' ');
k = aStr.substring(i).compareTo(bStr.substring(j));
</PRE>
Try checking the value of i and j before using them. If you attempt to use these as arguments to a function and they don't have valid values, you would get a NullPointerException.
 
Sheriff
Posts: 9109
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
sunilchandwani,
Please read this page and register properly.
Thanks.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic