编写JAVA程序时,出错提示:使用未经检查或不安全操作;要了解详细信息,请使用-Xlink:unchecked重新编译
importjava.util.*;classTreeSettest{publicstaticvoidmain(String[]args){TreeSet<Object>...
import java.util.*;
class TreeSettest
{
public static void main(String[] args)
{
TreeSet<Object> ts=new TreeSet<Object>(new student.studentComparator());
ts.add(new student(1,"zhangsan"));
ts.add(new student(2,"lisi"));
ts.add(new student(3,"wangdu"));
ts.add(new student(2,"ax"));
Iterator it=ts.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
class student implements Comparable
{
int num;
String name;
student(int num,String name)
{
this.num=num;
this.name=name;
}
static class studentComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
student s1=(student)o1;
student s2=(student)o2;
int result=s1.num>s2.num?1:(s1.num<s1.num?-1:0);
if(result==0)
{
result=s1.name.compareTo(s2.name);
}
return result;
}
}
public String toString()
{
return "num="+num+","+"name="+name;
}
public int compareTo(Object o)
{
student s=(student)o;
if(num>s.num)
{
return 1;
}
else if(num<s.num)
{
return -1;
}
else
return 0;
}
}
注意,我这里初始化
TreeSet<Object> ts=new TreeSet<Object>(new student.studentComparator());
的时候,想传递实现了Comparator接口的比较器对象student.studentComparator();
把student.studentComparator()去掉,是没有这个警告的,加上之后就有警告;
我现在的目的是想加上这个比较器对象后,没有警告提示 展开
class TreeSettest
{
public static void main(String[] args)
{
TreeSet<Object> ts=new TreeSet<Object>(new student.studentComparator());
ts.add(new student(1,"zhangsan"));
ts.add(new student(2,"lisi"));
ts.add(new student(3,"wangdu"));
ts.add(new student(2,"ax"));
Iterator it=ts.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
class student implements Comparable
{
int num;
String name;
student(int num,String name)
{
this.num=num;
this.name=name;
}
static class studentComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
student s1=(student)o1;
student s2=(student)o2;
int result=s1.num>s2.num?1:(s1.num<s1.num?-1:0);
if(result==0)
{
result=s1.name.compareTo(s2.name);
}
return result;
}
}
public String toString()
{
return "num="+num+","+"name="+name;
}
public int compareTo(Object o)
{
student s=(student)o;
if(num>s.num)
{
return 1;
}
else if(num<s.num)
{
return -1;
}
else
return 0;
}
}
注意,我这里初始化
TreeSet<Object> ts=new TreeSet<Object>(new student.studentComparator());
的时候,想传递实现了Comparator接口的比较器对象student.studentComparator();
把student.studentComparator()去掉,是没有这个警告的,加上之后就有警告;
我现在的目的是想加上这个比较器对象后,没有警告提示 展开
4个回答
展开全部
java中任何类都是Object 类的子类,所以TreeSet<Object>的<>里跟不写 一样,任何类型都可以装进去。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
初始化的时候改成这样:
TreeSet<student> ts=new TreeSet<student>();
TreeSet<student> ts=new TreeSet<student>();
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
在方法头部加个@SuppressWarnings("unchecked")
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询