1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Adding elements to arrayList

  1. Apr 22, 2017 #1
    1. The problem statement, all variables and given/known data
    Now we are going to use the design pattern for collecting objects. We are going to model a hospital nursery filled with newborn babies. A Nursery uses an ArrayList to keep track of Newborn objects. You will write both a Nursery class and a Newborn class.

    A Newborn has a name and a length. Provide a constructor that takes name and length, in that order. Provide getters and setters for the instance variables. This is the design pattern for managing properties of objects.

    A Nursery has a constructor that takes no parameters. Remember it must initialize the instance variable

    It has methods

    • add() Adds the specified Newborn to the Nursery
    • remove() Removes the first Newborn in the list with the specified name.
    • contains() determines if a Newborn with a given name is in the Nursery. Returns true if a Newborn with that name is in the Nursery. Otherwise false.
    • nameList() gets an ArrayList names of the Newborn in the Nursery.
    Provide Javadoc for both classes.

    2. Relevant equations
    We went over static methods and variables and constants before this lesson.

    3. The attempt at a solution
    Code (Text):
    import java.util.ArrayList;

    public class Nursery
    {
        private ArrayList<Newborn> nursery;

        public Nursery()
        {
            nursery = new ArrayList<>();
        }

        /**
         * @param n the newborn object to be added to the end of the nursery array.
         */
        public void add(Newborn n)
        {
            nursery.add(n);
        }

        public void remove(String target)
        {
            boolean found = false;
            int i = 0;
            while(!found && i < nursery.size() - 1)
            {
                if(nursery.get(i).getName().equals(target))
                {              
                    nursery.remove(nursery.get(i));
                    found = true;
                }
                else
                {
                    i++;
                }
            }

        }

        public boolean contains(String target)
        {
            for(Newborn n : nursery)
            {
                if(n.getName().equals(target))
                {
                    return true;
                }
            }
            return false;
        }

        public ArrayList<String> nameList()
        {
            ArrayList<String> storage = new ArrayList<>();
            for(Newborn n : nursery)//for each newborn in nursery
            {
                storage.add(n.getName());//add their name to storage...it only adds the first name each iteration
            }

            return storage;//return storage
        }
    }
    My problem so far is that in my add method, whenever I add a Newborn object, it replaces any previously stored objects in the nursery instance variable with whatever i'm trying to add. Here is the tester with the results to show what i'm talking about;

    Code (Text):
    import java.util.ArrayList;
    /**
     * Tester for Nursery
     */
    public class NurseryTesterFinal
    {
        public static void main(String[] args)
        {
            Nursery nursery = new Nursery();
            nursery.add(new Newborn("Lin", 17.4));
            nursery.add(new Newborn("Taran", 21.75));
            nursery.add(new Newborn("Sarah", 19));
            nursery.add(new Newborn("Miguel", 18.1));
            nursery.add(new Newborn("Sarah", 20.2));
           
           
            System.out.println(nursery.nameList());
            System.out.println("Expected: [Lin, Taran, Sarah, Miguel, Sarah]");
           
            nursery.remove("Sarah");
            System.out.println(nursery.nameList());
            System.out.println("Expected: [Lin, Taran, Miguel, Sarah]");
           
            nursery.remove("Lin");
            System.out.println(nursery.nameList());
            System.out.println("Expected: [Taran, Miguel, Sarah]");
           
            nursery.add(new Newborn("Aruna", 17.80));
           
            System.out.println(nursery.contains("Sarah"));
            System.out.println("Expected: true");
            System.out.println(nursery.contains("Kellan"));
            System.out.println("Expected: false");
           
            System.out.println(nursery.nameList());
            System.out.println("Expected: [Taran, Miguel, Sarah, Aruna]");

        }
    }
    Code (Text):
    [Sarah, Sarah, Sarah, Sarah, Sarah]
    Expected: [Lin, Taran, Sarah, Miguel, Sarah]
    [Sarah, Sarah, Sarah, Sarah]
    Expected: [Lin, Taran, Miguel, Sarah]
    [Sarah, Sarah, Sarah, Sarah]
    Expected: [Taran, Miguel, Sarah]
    false
    Expected: true
    false
    Expected: false
    [Aruna, Aruna, Aruna, Aruna, Aruna]
    Expected: [Taran, Miguel, Sarah, Aruna]
     


    Any advice on how to fix the add method?
     
  2. jcsd
  3. Apr 22, 2017 #2
    Somehow, instead of using an <Newborn>ArrayList, I used a <String>ArrayList.

    my new code looks like this

    Code (Text):

    import java.util.ArrayList;

    public class Nursery
    {
        private static ArrayList<String> nurseList;

        public Nursery()
        {
            nurseList = new ArrayList<>();
        }

        /**
         * @param n the newborn object to be added to the end of the nurseList array.
         */
        public static void add(Newborn n)
        {
            nurseList.add(n.getName());
        }
    ...
     
    and now it works. I'm really confused as to why this works when I use a string array list but not a Newborn array list.
     
  4. Apr 22, 2017 #3

    Mark44

    Staff: Mentor

    I don't have a Java system installed, so I can't test what I think is going on. In your code for the Nursery class, there is only one data member -- an ArrayList whose underlying type is Newborn. You don't show where this Newborn class is declared.
    Your constructor for a Nursery object should specify the underlying type for the ArrayList it allocates, something like this:
    Code (Java):
    public Nursery()
        {
            nursery = new ArrayList<Newborn>();
        }
    The net effect of this, I believe, is that when you first create an empty nursery object, your add() method doesn't work correctly, because your Nursery constructor isn't creating the right kind of ArrayList.
     
  5. Apr 22, 2017 #4
    Thank you for the response. I may have misinterpreted something you said;

    Code (Text):

    public class Nursery
    {
        private ArrayList<Newborn> nurseList;

        public Nursery()
        {
            nurseList = new ArrayList<Newborn>();
        }

        public void add(Newborn n)
        {      
            nurseList.add(n);
        }
    ...
     
    Here is also my Newborn class, sorry I forgot to include it.

    Code (Text):


    /**
     * construct a newborn object and have various methods to get and change
     * variables in the constructor
     */
    public class Newborn
    {
        private static String name;
        private static double length;
       
        /**
         * @param n is the name of the baby
         * @param l is the length of the baby
         */
        public Newborn(String n, double l)
        {
            name = n;
            length = l;
        }
       
        /**
         * @return the name of the baby
         */
        public String getName()
        {
            return name;
        }
       
        /**
         * Lets you set a new name for the baby
         * @param aName the new name of the baby
         */
        public void setName(String aName)
        {
            name = aName;
        }
       
        /**
         * @return the length of the baby
         */
        public double getLength()
        {
            return length;
        }
       
        /**
         * Lets you change the length of the baby
         * @param aLength new length of the baby
         */
        public void setLength(double aLength)
        {
            length = aLength;
        }
           
    }
     
    The tester still returns the same array of [Sarah, Sarah, Sarah, Sarah, Sarah] and similar to the other attempts to add.

    but when I change the instance variables in my Newborn class to this

    Code (Text):

    public class Newborn
    {
        private String name;
        private double length;
     
    and put the Nursery class as you suggested, the tester passes every test. I'm not sure why the them being static variables made it output what it did.


    Edit: just looked at the lecture from few days ago, it said that creating static variables is almost never a good idea.. and I guess that's what I did.
     
    Last edited: Apr 22, 2017
  6. Apr 22, 2017 #5

    Mark44

    Staff: Mentor

    First version:
    Code (Java):
    public class Newborn
    {
        private static String name;
        private static double length;
        ...
    New version:
    Code (Java):
    public class Newborn
    {
        private String name;
        private double length;
        ...
    Making the name and length members of the Newborn class static means that all instances of the Newborn class share the same string (and length). When you create new Newborn instances with your earlier version, the new instances overwrite the name and length members.
     
  7. Apr 22, 2017 #6

    Thank you, that makes it clear what was happening.
     
  8. Apr 22, 2017 #7

    Mark44

    Staff: Mentor

    I didn't explicitly say it, and I think you get it, but it won't hurt to add this -- by removing the "static" storage class from the name and length members, each Newborn instance now has its own unshared name and length data member.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted



Similar Discussions: Adding elements to arrayList
  1. Adding phasors (Replies: 3)

  2. JAVA ArrayList help (Replies: 5)

Loading...