Array Being Overwritten with Last Index in Loop

只愿长相守 提交于 2019-12-25 14:49:05

问题


I'm working on code that takes two arrays with strings (the strings are just sentences) and allocates them to classes which are held in another array (The Sentence class array shown below in the code).

So here's my problem. When popList() is called, the for loop runs through twice and works fine, putting the first index of addStrings and addTranslation into the first class in the array. However, when the loop indexes up and runs temp.sentence = addStrings[1] again, it OVERRIDES the first class's .sentence also. Then when temp.translations = addTranslations[1] runs again it OVERRIDES the first class's .translation.

So by the end of the loop, all of the arrays are filled with the same thing: the last index of addStrings and addTranslation. Every time it loops it overwrites all the indices before it with the index it's supposed to be putting in.

Anyone know what the problem is here? Thanks!

public class Sentence {
public String sentence;
public String translation;
Sentence() {
    sentence = " ";
    translation = " ";
}
}

    private void popStrings() {
    addStrings[0] = "我是你的朋友。";  addTranslations[0] = "I am your friend.";
    addStrings[1] = "你可以帮助我吗?"; addTranslations[1] = "Could you help me?";
    addStrings[2] = "我不想吃啊!";   addTranslations[2] = "I don't want to eat!";
}
//Fill Sentence array with string and translation arrays
private void popList() {
    int i = 0;
    Sentence temp = new Sentence();
    for(i = 0; i < addStrings.length && i < addTranslations.length ; i++) {
        temp.sentence = addStrings[i];
        temp.translation = addTranslations[i];
        sentences[i] = temp;
    }
}

回答1:


You need to create new Sentence() inside the loop:

for(i = 0; i < addStrings.length && i < addTranslations.length ; i++) {
    Sentence temp = new Sentence();
    temp.sentence = addStrings[i];
    temp.translation = addTranslations[i];
    sentences[i] = temp;
}

Otherwise you set sentence and translation continuously in the same object.



来源:https://stackoverflow.com/questions/6528088/array-being-overwritten-with-last-index-in-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!