java:解析值时我只得到一个元素

时间:2012-03-05 11:22:12

标签: java

当这个程序运行时,我只得到一个名字而不是两个名字 那就是输出只有Pavan

import java.util.ArrayList;
import java.util.List;

public class Work {

    public static void main(String args[]) {

        User user1 = new User();
        User user2 = new User();

        user1.setName("Pavan");
        user2.setName("Palla");

        List userItems = new ArrayList();
        userItems.add(user1);
        userItems.add(user2);

        UserlistItem[] userlistitem = new UserlistItem[userItems.size()];

        for (int i = 0; i < userItems.size(); i++) {

            User user = (User) userItems.get(i);

            userlistitem[i] = new UserlistItem();

            userlistitem[i].setUser(user);

        }

        Userlist userlistm = new Userlist();
        userlistm.setUserlistItem(userlistitem);

        UserlistItem[] ravi = userlistm.getUserlistItem();

        Userlists lists = new Userlists();

        lists.setUserlist(new Userlist[] { userlistm });

        Userlist[] main = lists.getUserlist();

        for (int i = 0; i < main.length; i++) {
            System.out.println("Pavan"
                    + main[i].getUserlistItem()[i].getUser().getName());
        }


}

public class User {

     private String      name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}


public class UserlistItem {
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    } 


}



import java.io.Serializable;

public class Userlist {

    private static final long serialVersionUID = 1L;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public UserlistItem[] getUserlistItem() {
        return UserlistItem;
    }

    public void setUserlistItem(UserlistItem[] userlistItem) {
        UserlistItem = userlistItem;
    }

    private String id;
    private UserlistItem[] UserlistItem;

}



public class Userlists {

    private Userlist[] userlist;

    public Userlist[] getUserlist() {
        return userlist;
    }

    public void setUserlist(Userlist[] userlist) {
        this.userlist = userlist;
    }

}

1 个答案:

答案 0 :(得分:2)

首先,为什么不通过在发生打印的行上放置断点来调试代码?在main方法的第二个for循环中,main.length是1.将循环更改为下面的代码,它将完成。但是你的代码很混乱,我不确定你将如何跟踪你定义的类的更多对象。

for (int i = 0; i < main[0].getUserlistItem().length; i++) {
    System.out.println("Pavan"
            + main[0].getUserlistItem()[i].getUser().getName());
}