Join
Blogs
Questions
Videos
Tags
Members
Search
 
 
Create your own blog, earn points and get popular!

Comaparator Program error !!!

i am a beginner of java , i was trying to use comaparator for tree set to get reverse order sort for the following program but was getting error like ComparatorDemo.java uses unchecked or unsafe operations Recompile with -xlint : unchecked for details.


import java.util.*;
class MyComp implements Comparator

{
    public int compare(Object a , Object b)
    {
        String astr,bstr;
        astr = (String)a;
        bstr = (String)b;
        return bstr.compareTo(astr);
    }
}
public class ComparatorDemo
{
    public static void main(String args[])
    {
        TreeSet<String> ts = new TreeSet<String>(new MyComp());
        ts.add("D");
        ts.add("A");
        ts.add("O");
        ts.add("S");
        ts.add("N");
        ts.add("C");
        ts.add("B");
        Iterator i = ts.iterator();
        while(i.hasNext())
        {
            Object e = i.next();
            System.out.println(e+ " ");
        }
        System.out.println();
    }
}

 can any1 please help me out regarding the issue.....
No votes yet
Share this
1 answer
ravishnkr.m's picture
Hi the above code is working without errors. below is the few changes i made related to MyComp w.r.to Generics.

import java.util.Comparator;


class MyComp implements Comparator<String>

{
    public int compare(String a , String b)
    {
        String astr,bstr;
        astr = (String)a;
        bstr = (String)b;
        return bstr.compareTo(astr);
    }
}



import java.util.Iterator;
import java.util.TreeSet;

public class ComparatorDemo {
public static void main(String args[])
    {
        TreeSet<String> ts = new TreeSet<String>(new MyComp());
        ts.add("D");
        ts.add("A");
        ts.add("O");
        ts.add("S");
        ts.add("N");
        ts.add("C");
        ts.add("B");
        Iterator i = ts.iterator();
        while(i.hasNext())
        {
            Object e = i.next();
            System.out.println(e+ " ");
        }
        System.out.println();
    }
}
Your rating: None Average: 5 (1 vote)