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!

Simple Question about ArrayList class in java

  1. Sep 16, 2011 #1
    I am learning about the ArrayList class in my java programming II class.
    I am wondering why you would specify an arrayList to only contain, for example, strings:
    ArrayList <String> arrayName = new ArrayList <String> ();

    versus

    ArrayList arrayName = new ArrayList ();
    in which, to my knowledge you can use ANY object type you please or even, different types of objects

    Why would someone use the prior?

    Also, the default capacity of an ArrayList is 10. Meaning that is its size before expansion or contraction......why would anyone have a reason to change this capacity if you can just add or remove elements to the size you want?

    Thanks so much, my professor seemed to "not understand" my question (foreign folk)
    :p
    Amanda
     
  2. jcsd
  3. Sep 17, 2011 #2
    I probably won't explain this well, but I'll give it a try.

    Because you generally want to know what type of list you have, without having to check the type when you use it. So if you use this:

    ArrayList arrayName = new ArrayList ();

    Every time, you want to use an object in the class, you have to cast it back. And then you have to be aware what's in the list.

    Example1:
    Code (Text):
    ArrayList <String> arrayName = new ArrayList <String> ();
    arrayName.add("pf");
    arrayName.add("new string");

    So suppose you want to do something with the list, you can just do this:
    for (String value : arrayName){
        do something with value
    }
    Example2:
    Code (Text):
    ArrayList arrayName = new ArrayList();
    arrayName.add("pf");
    arrayName.add("new string");

    You can't use the for loop as you did in example 1 because the system doesn't know what type of list you have, so you would have to something like this:
    for (int i = 0; i < arrayName.size(); i++){
        String value = (String) arrayName.get(i);
        do something with value
    }
     
    Example3:
    Code (Text):
    ArrayList arrayName = new ArrayList();
    arrayName.add("pf");
    arrayName.add("new string");
    arrayName.add(56);

    for (int i = 0; i < arrayName.size(); i++){
        Object object = arrayName.get(i);
        if (object instanceof String){
            do something with object
        } else if (object instanceof Integer){
        //The more object you have, the more if else statement you need
    }
     
    Example1 is ideal. You know what type of object is in that list. It also prevent coders who come after you to add something other than string.

    Example 2 is ok. You have to do unnecessary casting. Doesn't prevent other coder from adding something else other than string. In that case, you would get a runtime error when you go through the loop.

    Example 3 is an extension of example 2. Suppose you want to add another type of object to the list, every time you want to use the object, you have to know what type of object is in the list.

    For performance and memory. The default size is 10. So if you add 11 object, what the system have to do is create a new list with a new size (I don't know what the size is...20? 30?). Then copy all the objects in the first list to the newly created list.

    For example, if you know well in advance that you will only have 13 objects in the list.

    Option1: Specify a size
    Code (Text):

    1. Create a new list, size 13
    2. Add all 13 objects
     
    Option2: Didn't specify a size
    Code (Text):

    1. Create a new list, size 10
    2. Add 10 objects
    3. Create new list with new size (when you add the 11th object)
    4. Copy all the objects in the first list
    5. Add the rest of the objects
    (6. Leave arraylist one for garbage college)
     
    Does that explain it?
     
    Last edited: Sep 17, 2011
  4. Sep 18, 2011 #3
    actually that was a perfect explanation, thank you! i just want to be very thorough with my understanding of this language. I just had the summer off between java classes so im a little rusty. I have another small question if you wouldnt mind helping me out?

    I am creating an arrayList to hold new objects [user requests to add a new soccer player[object] along with stats about the player[data fields], so ill be sending those objects [players] to an arraylist to store. at the end of the program i have to print the list of all the 'players' to the console....

    for example:
    if (answer.equals("add")) {
    //If user wants to add a new player to the list
    Player athlete = new Player(); //creating a new player referenced as 'athlete'
    //Prompt user to add statistics for player
    System.out.println("Please enter player's last name: \n");
    athlete.setLastName(input.next());
    //etc. etc. etc. until data fields are filled.

    now...before this IF statement i created an arraylist in the main method...
    so now...i would send athlete to the arrayList, correct?
    BUT...my question is...when the user wants to add ANOTHER player, since it is still going to be referenced as 'athlete' will it simply replace the old player in the list or is arrayList smart enough to store the old player and create a new slot for the new 'athlete'?

    My project is due in a few days and i dont want to create my entire application built on this fallacy if it will end up fundamentally wrong : (
    thank you so much again.
     
  5. Sep 18, 2011 #4
    When in doubt, test it. (Even if you're not in doubt, you should test it anyway to make sure it works the way you want. :biggrin:)

    If I understand correctly, your code look somewhat like this right?

    Code (Text):

    ArrayList<Player> playerList = new ArrayList<Player>();

    while(condition is true){
       if (answer.equals("add")) {
          //If user wants to add a new player to the list
          Player athlete = new Player(); //creating a new player referenced as 'athlete'
          //Prompt user to add statistics for player
          System.out.println("Please enter player's last name: \n");
          athlete.setLastName(input.next());

          //Add player to list
          playerList.add(athlete);
       }    
    }
     
    A simple to your question is no, it will not override the player you added. I don't really know how to explain this question, but I'll try. (Hopefully you can read my mind :blushing:)

    Let's get a few things clear:
    1. When you declare new Player(), you're asking the system for a new (i.e. not being used) memory space for the player.
    1a. The system will not override a memory space unless you tell it to (i.e. declare field as static)
    3. The garbage collector collects object that is not being referenced

    So in the code above, you're saying, if it's add:
    1. Can I have some memory space for a player (new Player)?
    2. Add data for the player
    3. Add it to the list, which means the memory space for the player you just create is being referenced by the list. So when you go back to step one and create a new Player, the system wouldn't use that same memory space because it's already being used (i.e. not freed).

    Lolz, does that makes any kind of sense?
     
  6. Sep 19, 2011 #5
    gosh, thank you so much. youre really good at explaining the concept. im really glad to hear my idea worked out and my implementation of the coding is going smoothly. my project works fine : ) thanks, i owe you!
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Simple Question about ArrayList class in java
  1. About Java classes (Replies: 11)

  2. JAVA ArrayList help (Replies: 5)

Loading...