Why Use Generics in Java ArrayLists and Modify Default Capacity?

  • Comp Sci
  • Thread starter kirkulator
  • Start date
  • Tags
    Class Java
In summary: System.out.println("adding new player at index " + answer.intValue()); }else { //If user wants to print the list of all players ... System.out.println("printing list of players at index " + answer.intValue()); //System.out.println(answer.toString()); }In summary, the ArrayList class allows you to store any object type in a list. You can specify a size for the list before adding or removing objects, and the list has a default capacity of 10.
  • #1
kirkulator
33
0
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
 
Physics news on Phys.org
  • #2
I probably won't explain this well, but I'll give it a try.

kirkulator said:
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?
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:
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:
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:
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.

kirkulator said:
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

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:
1. Create a new list, size 13
2. Add all 13 objects

Option2: Didn't specify a size
Code:
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:
  • #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 I am a little rusty. I have another small question if you wouldn't 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 don't want to create my entire application built on this fallacy if it will end up fundamentally wrong : (
thank you so much again.
 
  • #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:
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?
 
  • #5
gosh, thank you so much. youre really good at explaining the concept. I am 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!
 

Related to Why Use Generics in Java ArrayLists and Modify Default Capacity?

1. What is an ArrayList in Java?

An ArrayList in Java is a resizable array that can hold a collection of objects. It is a part of the Java Collections Framework and provides dynamic storage for elements, allowing for easier manipulation and retrieval of data.

2. How do you declare an ArrayList in Java?

To declare an ArrayList in Java, you first need to import the java.util.ArrayList class. Then, you can declare the ArrayList using the following syntax: ArrayList<DataType> listName = new ArrayList<DataType>();

3. How do you add elements to an ArrayList in Java?

You can add elements to an ArrayList in Java using the add() method. This method takes in the element you want to add as a parameter and inserts it at the end of the ArrayList. Alternatively, you can also use the add(index, element) method to specify the index at which you want to add the element.

4. How do you retrieve elements from an ArrayList in Java?

To retrieve elements from an ArrayList in Java, you can use the get(index) method. This method takes in the index of the element you want to retrieve and returns the element at that index. You can also use a for loop to iterate through the ArrayList and retrieve each element one by one.

5. How do you remove elements from an ArrayList in Java?

You can remove elements from an ArrayList in Java using the remove(index) method. This method takes in the index of the element you want to remove and deletes it from the ArrayList. Alternatively, you can also use the remove(element) method to remove a specific element from the ArrayList.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
1
Views
944
  • Engineering and Comp Sci Homework Help
Replies
1
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
1K
  • Programming and Computer Science
Replies
5
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
5
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
10
Views
10K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
4
Views
2K
Back
Top