Results 1 to 7 of 7
  1. #1
    Cod
    Cod is offline Member
    Join Date
    Nov 2009
    Location
    Honolulu, HI
    Posts
    59
    Rep Power
    0

    Default Objects of ArrayList Overwriting

    I'm having trouble getting new objects to add to an ArrayList. Intead, everytime a new object is created and added, it overwrites the first object. So if I read in four lines from a text file and make them into four objects, each overwrites the previous and only the last object is printed. I can print out the contents correctly if I move the println statement within the if-loop; however, I need all the objects to saved to the list for searching (later implementation). i believe it has something to do with the instances of the object, but I'm a little confused about how to fix it. Here's the portion of the code I'm looking at:

    Java Code:
            if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                File file = fileChooser.getSelectedFile();
                Scanner scanner = new Scanner(new FileReader(file));
                String currentLine;
                System.out.printf("%-20s %-20s %-20s\n", "Author Index", "Author Name", "Address");
                while (scanner.hasNextLine()) {
                    currentLine = scanner.nextLine();
                    if (currentLine.startsWith("/") || currentLine.trim().isEmpty())
                        continue;
                    character = currentLine.charAt(0);
    
                    if (character == 'a') {
                        currentLine = currentLine.substring(4);
                        tempAuthorArray = currentLine.split("\\s*:\\s*");
                        authorIndex = Integer.parseInt(tempAuthorArray[0]);
                        newAuthor.setAuthorIndex(authorIndex);
                        authorName = tempAuthorArray[1];
                        newAuthor.setAuthorName(authorName);
                        address = tempAuthorArray[2];
                        newAuthor.setAddress(address);
                        authorList.add(newAuthor);
                    } else if (character == 'b') {
                        currentLine = currentLine.substring(4);
                        tempBookArray = currentLine.split("\\s*:\\s*");
                        //System.out.println(Arrays.toString(tempBookArray));
                    } else {
                        scanner.nextLine();
                    }
                }
            } else {
                System.out.println("No file selected.");
            }
            
            // Print contents of ArrayList
            for (int i = 0; i < authorList.size(); i++) {
                System.out.printf("%-20s %-20s %-20s\n", newAuthor.getAuthorIndex(), newAuthor.getAuthorName(), newAuthor.getAddress());
            }
    Any guidance is greatly appreciated.

  2. #2
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    922
    Rep Power
    2

    Default Re: Objects of ArrayList Overwriting

    You never instantiate a new Author. You keep using the same instance. Create new instances *inside* the loop.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  3. #3
    Cod
    Cod is offline Member
    Join Date
    Nov 2009
    Location
    Honolulu, HI
    Posts
    59
    Rep Power
    0

    Default Re: Objects of ArrayList Overwriting

    Quote Originally Posted by SurfMan View Post
    You never instantiate a new Author. You keep using the same instance. Create new instances *inside* the loop.
    Thanks for the reply. So after authorList.add(newAuthor), i could put something like newAuthor = new Author(authorIndex, name, address): (same constructor used as instance variable)? Would that maintain the arraylist throughout the program, until it exits?

    The next part of this project deals with searching and a GUI, so I'm trying to ensure i got the reading from the input file down first. And this may be beyond the scope of a beginning OOP project, but is there an easy way to save the contents of an arraylist from one running to another? Basically, everytime I run the code, the arraylist picks up where it last left off (saving previous entries).

  4. #4
    Cod
    Cod is offline Member
    Join Date
    Nov 2009
    Location
    Honolulu, HI
    Posts
    59
    Rep Power
    0

    Default Re: Objects of ArrayList Overwriting

    So I took out authorList.add(newAuthor) and tried authorList.add(new Author(newAuthor)) and the problem still persists. I get the correct arraylist size, but all the objects are the same.

  5. #5
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    922
    Rep Power
    2

    Default Re: Objects of ArrayList Overwriting

    If new Author(newAuthor) is a so called copy constructor, then the data will be the same since newAuthor does not get changed.

    The general idea of adding items in a loop looks like this:
    Java Code:
    List<Author> result = new ArrayList<>();
    while ( myLoopNeedsToRun ) {
        Author au = new Author();
        au.setName(...);
        ...
       
        result.add(au);
    }
    //use result here...
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  6. #6
    Cod
    Cod is offline Member
    Join Date
    Nov 2009
    Location
    Honolulu, HI
    Posts
    59
    Rep Power
    0

    Default Re: Objects of ArrayList Overwriting

    Here's the constructor I'm using (from the Author class):
    Java Code:
        public Author(int authorIndex, String authorName, String address) {
            //Initialize variables
            this.bookList = new ArrayList<>();
            this.authorIndex = 0;
            this.authorName = new String();
            this.address = new String();
        }
    Is this where the issue is being caused? Did I initialize the variables incorrectly? Please ignore that bookList arraylist as its for a later / different part of the project.

    I'm really trying to understand the object stuff, but I'm confused as hell.

    Thanks for assisting.

  7. #7
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    922
    Rep Power
    2

    Default Re: Objects of ArrayList Overwriting

    Your constructor doesn't work the way you expect it. You must assign the parameters to a field:
    Java Code:
    public Author(int authorIndex, String authorName, String address) {
        //Initialize variables
        this.bookList = new ArrayList<>();
        this.authorIndex = authorIndex;
        this.authorName = authorName;
        this.address = address;
    }
    Note that this.authorIndex points to the field and authorIndex (without the this.) points to the variable. If you really want, you could make the parameters standout by prefixing them:
    Java Code:
    public Author(int _authorIndex, String _authorName, String _address) {
        //Initialize variables
        this.bookList = new ArrayList<>();
        this.authorIndex = _authorIndex;
        this.authorName = _authorName;
        this.address = _address;
    }
    I don't do that myself, but in the beginning of coding, it might be useful.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

Similar Threads

  1. Use objects from an ArrayList
    By bobbytown in forum AWT / Swing
    Replies: 0
    Last Post: 01-13-2014, 12:49 PM
  2. Arraylist-Objects
    By ztomtomz in forum New To Java
    Replies: 5
    Last Post: 11-18-2012, 01:28 PM
  3. ArrayList with Objects the right approach?
    By scheffetz in forum New To Java
    Replies: 1
    Last Post: 03-25-2011, 09:26 AM
  4. Help with objects in ArrayList
    By BiteMuncher in forum New To Java
    Replies: 7
    Last Post: 02-21-2011, 11:55 AM
  5. ArrayList with different objects? Help
    By xtrmi in forum New To Java
    Replies: 4
    Last Post: 02-27-2009, 08:51 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •