使用Arrays和List正确循环构造

时间:2012-06-14 20:09:36

标签: java arrays list for-loop

在这个简单的例子中,我想创建一个String数组,其中填充了每个人在我的数据库中的第一个和最后一个。我知道我遗漏了一些非常明显的东西,因为我在以下循环方法中一直覆盖i。第二只眼肯定会有所帮助。

    /**
 * 
 * @return
 */
public String[] buildFullNameContainer(){

    List<Person> allPeople = Person.findAllPeople();
    String[] peopleContainer = new String[] {""};
    String fullName = "";



        for (int i = 0; i < peopleContainer.length; i++) {
            for (Person person : allPeople) {
                fullName = person.getFirstName() + " " + person.getLastName();  
                peopleContainer[i] = fullName; 

            }
        }
    return peopleContainer;
}

5 个答案:

答案 0 :(得分:4)

您的数组始终只有一个元素 - 您应该将其创建为与列表相同的长度。另外,你有两个嵌套循环无缘无故,我在fullName变量中看不到任何意义。这是我使用的代码:

String[] peopleContainer = new String[allPeople.size()];

for (int i = 0; i < peopleContainer.length; i++) {
    Person person = allPeople.get(i);
    peopleContainer[i] = person.getFirstName() + " " + person.getLastName();
}

答案 1 :(得分:3)

替换

String[] peopleContainer = new String[] {""};

String[] peopleContainer = new String[allPeople.size()];

另外,按如下方式编辑循环:

for(int i = 0; i < peopleContainer.length; i++)
{
    Person person = allPeople.get(i);
    fullName = person.getFirstName() + " " + person.getLastName();  
    peopleContainer[i] = fullName;  
}

答案 2 :(得分:0)

我认为这需要改变:

String[] peopleContainer = new String[] {""};

要:

String[] peopleContainer = new String[allPeople.size()];

答案 3 :(得分:0)

您循环遍历结果数组,而不是源数据集合。您必须首先正确调整数组的大小,然后循环遍历数组或列表的大小。不需要嵌套。

public String[] buildFullNameContainer(){

    List<Person> allPeople = Person.findAllPeople();
    String[] peopleContainer = new String[allPeople.size()];
    for (int i = 0; i < peopleContainer.length; i++) {
        Person person = allPeople.get(i);
        String fullName = person.getFirstName() + " " + person.getLastName();  
        peopleContainer[i] = fullName; 
    }
return peopleContainer;
}

答案 4 :(得分:0)

试试这个。

    List<Person> allPeople = Person.findAllPeople();
    String[] peopleContainer = new String[allPeople.size()];

    for (int i=0;i < allPeople.size();i++;) {
          Person person=allPeople.get(i);
          fullName = person.getFirstName() + " " + person.getLastName();  
          peopleContainer[i] = fullName; 
    }