tags:

views:

172

answers:

6

I have code in Java that should make multiple objects within a for-loop, then add each object into an array. However, the code just copies the same (which is the last in the for-loop) object into each index i in the array once the loop ends.

How can I correct this to have each separate object in its correct index in the array?

I can post code if necessary, but it would be nice if someone could give me an example of how this would work.

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();
            }
        }
    }

Thanks a ton!

Here is where I print some object info to the console.

System.out.println(getSong(1).getTitle());
System.out.println(getSong(4).getTitle());
A: 

Should be as simple as

for (int ii = 0; ii < yourArray.length; ii++) {
    yourArray[ii] = new YourObject();
}

We can't tell you what the problem is without seeing your code.

Josh McFadden
A: 
for (int i=1; i<file.listFiles().length-1; i++) { 
        if (fileList[i].isFile() && !fileList[i].isHidden() && fileList[i].getName().substring(fileList[i].getName().length()-4).equalsIgnoreCase(".mp3")) {
            try {

                Song s = new Song(fileList[i]);
                songs[i] = s;   

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (TagException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            // Make counter to determine size of playlistInfo array
            // Use Comparator to sort
        }
    }
Rodney Keeling
-1 - Don't post followups as answers.
Stephen C
Sorry, I'm new. Where should I post it? Thanks.
Rodney Keeling
You should edit your own question to add the block of code. Not sure if you can do it with your reputation thought.
Ravi Wallau
I already edited your question with the code, Just delete this answer.
Soufiane Hassou
@Stephen: Maybe remove the downvote since he's trying to learn? I don't want to upvote to cancel out because that would be a net reward :-)
Eric J.
Thanks guys! I do not know how to delete the post though. I only see edit.
Rodney Keeling
A: 

Your code

int i=1; i<file.listFiles().length-1

Should probably be

int i=0; i<file.listFiles().length

You are starting from the second element in your array (since the first one is zero) and ending one early because the '<' and the '-1' each make you stop one short of .length, for a total of 2 short (and since the array is zero based, you only want to stop one short).

Eric J.
Yeah that's how it was before, but I was getting a NullPointerException on the 0th index of my array for some reason, which is another problem in itself! :P
Rodney Keeling
Add something to check if the fileList[i] is not null. You should start from zero.
Ravi Wallau
@Rodney: The way you have the loop running now is almost certainly wrong. I think Ravi's suggestion is a good one. If you're still getting a null pointer exception, tell us exactly what line of your code throws it.
Eric J.
I will update the code to what I have changed it to. The filter for a null element is now there. Thanks! Also, when the //playlistInfo[i] = fileList[i].getName(); line is uncommented, I get an ArrayIndexOutOfBounds exception.
Rodney Keeling
@Rodney: What value of i gives you taht ArrayIndexOutOfBoundsException? Can you inspect fileList[] in your debugger to see that you have a value assigned to each element of the array, and that the array has the size you expect it to have?
Eric J.
A: 

You will have empty items on your songs array if your if conditions don't evaluate to true. I would recommend using an ArrayList class and add the items to there as you find them:

List<Song> songs = new ArrayList<Song>();
for (int i=1; i<file.listFiles().length-1; i++) {
    if (fileList[i].isFile() && !fileList[i].isHidden() && fileList[i].getName().substring(fileList[i].getName().length()-4).equalsIgnoreCase(".mp3")) {
        songs.add(new Song(fileList[i]));
    }
}

I would also recommend that you:

  • Use the method File.listFiles to get the files that match a given criteria; You have a bunch of pre-defined filters in the package org.apache.commons.io.filefilter in the Commons IO project;
  • Check the file name length before making your comparison or using the FilenameUtils.getExtension method in the Commons IO library to get the file extension (you may think it is overkill, but...);
  • Using lists instead of arrays;
  • I don't think your instantiation of the Song class is prone to generate exceptions. A try...catch block in a higher level could be more appropriate. And your treatment to the exception is completely wrong, if you won't do more to it than simply printing its stack trace, it is better not to catch it.

About your problem, I am not sure how all the generated objects would be the same, except if your fileList array contains the same element in all positions.

Ravi Wallau
Thanks for all of the advice. I will definitely handle the exception in a more appropriate manner; however, I am not to that step yet. And I have switched to arraylists, but I still get the same object in all indexes. Again, thanks!
Rodney Keeling
Perhaps then you should look outside the loop for your problem. You will probably have to debug it or add print statements everywhere. I would make sure that the same file doesn't fill your entire fileList array, and that the constructor of the Song class actually uses the file you are sending to it. Also, check if the method you are using to check that each file is different from the other is working correctly.
Ravi Wallau
A: 

The code that you are using to create Song objects and assign then to songs is basically correct. Your problem is elsewhere:

  • The for statement is almost certainly incorrect, the index of the first element of an array is 0 and the index of the last element is array.length - 1. You are iterating from 1 to array.length - 2.

  • If you get a NullPointerException in the loop it is most likely because either fileList is null or it contains a null element.

  • If the fileList array contains directories, hidden files or files that don't match, then the songs array will have a null at that the corresponding position. THAT could be the cause of NullPointerExceptions ... if you don't check before printing the array entries.

And I'd note that this code:

System.out.println(getSong(1).getTitle());
System.out.println(getSong(4).getTitle());

will not tell you that the Song objects are the same or different. Rather it will just tell you if the two Song objects have titles with the same characters.

This will tell you if the Song objects are different:

if (getSong(1) != getSong(4)) {
    System.err.println("They are different");
}
Stephen C
I have added another filter where null elements will not be added to the list, and that part works now. Also, I changed the limits of the for loop. Thanks!
Rodney Keeling
Thanks for the code snippet! The result was "They are different"
Rodney Keeling
A: 

I've corrected the issue. A few of my class variables were static, which was causing the problem of creating new objects in each index in my arraylist. I apologize for any troubles this has caused anyone.

Thanks for everyone's help! :]

Rodney Keeling
As I said, sometimes you should look outside the look to get the solution for a given problem :-).
Ravi Wallau