黑马程序员技术交流社区

标题: 关于迭代器的( next().成员变量 )的问题 [打印本页]

作者: 回忆初中时候    时间: 2014-4-12 23:19
标题: 关于迭代器的( next().成员变量 )的问题
import java.util.*;
class  HashSetDemo
{
        public static void main(String[] args)
        {
                HashSet ht = new HashSet();
                ht.add(new Student("小五",19));
                ht.add(new Student("地方",139));
                ht.add(new Student("小df",129));
                ht.add(new Student("小dfaaadf",197));
                Iterator it = ht.iterator();
                while(it.hasNext())
                {
                        System.out.println(it.next().name);
                        /*提示找不到符号,为什么it.next().getClass()方法返回的是Student对象,为什么it.next().name这条语句会出现错误*/
                }
        }
}
class Student
{
        public String name;
        public int num;
        public Student(String name,int num)
        {
                this.name = name;
                this.num = num;
        }
}
作者: 程序爱好者    时间: 2014-4-12 23:41
ht.add(new Student("小五",19));   
//这句话就是
Object obj=new Student("小五",19)     
ht.add(obj);
转换成了Object类型了
所以 it.next()  返回的也是Object类型,Object类中没有name和num属性 所以点不出来
作者: Monkey·D·Chas    时间: 2014-4-13 00:37
你需要把it.next();强转成你需要的类型。
因为默认的it.next();是Object类型的
或者你定义泛型

  1. import java.util.*;
  2. class  HashSetDemo
  3. {
  4.         public static void main(String[] args)
  5.         {
  6.                 HashSet <Student> ht = new HashSet<Student>();
  7.                 ht.add(new Student("小五",19));
  8.                 ht.add(new Student("地方",139));
  9.                 ht.add(new Student("小df",129));
  10.                 ht.add(new Student("小dfaaadf",197));
  11.                 Iterator<Student> it = ht.iterator();
  12.                 while(it.hasNext())
  13.                 {
  14.                         System.out.println(it.next().name);
  15.                         /*提示找不到符号,为什么it.next().getClass()方法返回的是Student对象,为什么it.next().name这条语句会出现错误*/
  16.                 }
  17.         }
  18. }
  19. class Student
  20. {
  21.         public String name;
  22.         public int num;
  23.         public Student(String name,int num)
  24.         {
  25.                 this.name = name;
  26.                 this.num = num;
  27.         }
  28. }
复制代码

作者: 回忆初中时候    时间: 2014-4-13 15:53
Monkey·D·Chas 发表于 2014-4-13 00:37
你需要把it.next();强转成你需要的类型。
因为默认的it.next();是Object类型的
或者你定义泛型

谢谢 懂了
作者: 回忆初中时候    时间: 2014-4-13 15:54
程序爱好者 发表于 2014-4-12 23:41
ht.add(new Student("小五",19));   
//这句话就是
Object obj=new Student("小五",19)     

谢谢 懂了
作者: 回忆初中时候    时间: 2014-4-13 15:56
程序爱好者 发表于 2014-4-12 23:41
ht.add(new Student("小五",19));   
//这句话就是
Object obj=new Student("小五",19)     

:dizzy:请问为什么it.next().getClass()方法返回的是Student对象??




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2