码迷,mamicode.com
首页 > 编程语言 > 详细

java中类的提升所导致的问题

时间:2016-06-11 15:56:12      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:

import java.util.*;
class Person
{
    private String name;
    private int age;
    Person(String name,int age)
    {
        this.name = name;
        this.age = age;
    }
    public String getName()
    {
        return name;
    }
    public int getAge()
    {
        return age;
    }
}
class Demo 
{
        public static void main(String[] args) 
        {
            ArrayList al = new ArrayList();
            al.add(new Person("lisi01",30));
            al.add(new Person("lisi02",32));
            al.add(new Person("lisi03",33));
            al.add(new Person("lisi04",35));
            Iterator it = al.iterator();
            while(it.hasNext())
            {
                System.out.println(it.next().getName());
            }
        }
        
}

使用it.next().getName()会导致问题,

原因是将  “lisi01”,30  存入ArrayList中时会将其提升为Object,it.next()返回的是Object类型的对象,Object中没有getName方法,

应强制转换:

while(it.hasNext())
{
    Person p = (Person)it.next();
    System.out.println(it.next().getName());
}

 

java中类的提升所导致的问题

标签:

原文地址:http://www.cnblogs.com/cdx19971126/p/5575402.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!