Android 正在使用循环中的最后一个索引覆盖数组

Android 正在使用循环中的最后一个索引覆盖数组,android,loops,overriding,Android,Loops,Overriding,我正在编写一段代码,它接受两个带字符串的数组(字符串只是句子),并将它们分配给另一个数组中的类(代码中下面显示的句子类数组) 这就是我的问题。调用popList()时,for循环运行两次并正常工作,将addStrings和addTranslation的第一个索引放入数组中的第一个类中。但是,当循环索引向上并再次运行temp.sential=addStrings[1]时,它也会覆盖第一个类的.sential。然后,当temp.translations=addTranslations[1]再次运行时

我正在编写一段代码,它接受两个带字符串的数组(字符串只是句子),并将它们分配给另一个数组中的类(代码中下面显示的句子类数组)

这就是我的问题。调用popList()时,for循环运行两次并正常工作,将addStrings和addTranslation的第一个索引放入数组中的第一个类中。但是,当循环索引向上并再次运行temp.sential=addStrings[1]时,它也会覆盖第一个类的.sential。然后,当temp.translations=addTranslations[1]再次运行时,它将覆盖第一个类的.translation

因此,在循环结束时,所有数组都填充了相同的内容:addStrings和addTranslation的最后一个索引。每次循环时,它都会用它应该放入的索引覆盖它之前的所有索引

有人知道这里有什么问题吗?谢谢

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;
    }
}
公共类语句{
公共字符串句;
公共字符串翻译;
第()句{
句子=”;
翻译=”;
}
}
私有void字符串(){
添加字符串[0]=”我是你的朋友。";  addTranslations[0]=“我是你的朋友。”;
addStrings[1]=”你可以帮助我吗?“addTranslations[1]=“你能帮我吗?”;
addStrings[2]=”我不想吃啊!“addTranslations[2]=“我不想吃!”;
}
//用字符串和翻译数组填充句子数组
私有void popList(){
int i=0;
句子临时=新句子();
对于(i=0;i
您需要在循环中创建新的句子()

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;
}
for(i=0;i

否则,您将在同一对象中连续设置句子和翻译。

这对我来说很奇怪,我认为所有内容都在索引中,临时值正在更改…仍然不知道它对之前的索引有何影响。无论如何,感谢它现在起作用。临时没有索引…通过编写您所说的temp.句子=xxxx-请设置发送然后将语句[i]设置为temp。在java中,对象是引用,所以实际上句子中的所有元素都引用同一个对象(temp)。