我有 Java 代码,应该在 for 循环中创建多个对象,然后将每个对象添加到数组中。然而,一旦循环结束,代码只是将相同的(for 循环中的最后一个)对象复制到数组中的每个索引 i 中。
如何更正此问题以使每个单独的对象位于数组中的正确索引中?
如果需要,我可以发布代码,但如果有人能给我一个例子来说明它是如何工作的,那就太好了。
for (int i = 0; i < file.listFiles().length; i++) {
if (fileList[i].isFile() && !fileList[i].isHidden() && fileList[i].getName().substring(fileList[i].getName().length() - 4).equalsIgnoreCase(".mp3")
&& !fileList[i].equals(null)) {
try {
songs.add(new Song(fileList[i]));
//System.out.println(songs[i].getTitle());
//playlistInfo[i] = fileList[i].getName();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TagException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
这是我将一些对象信息打印到控制台的地方。
System.out.println(getSong(1).getTitle());
System.out.println(getSong(4).getTitle());
最佳答案
应该很简单
for (int ii = 0; ii < yourArray.length; ii++) {
yourArray[ii] = new YourObject();
}
如果没有看到您的代码,我们无法告诉您问题所在。
关于java - 在 for 循环中创建多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2394956/