Why Use Generics in Java ArrayLists and Modify Default Capacity?

  • Context: Comp Sci 
  • Thread starter Thread starter kirkulator
  • Start date Start date
  • Tags Tags
    Class Java
Click For Summary

Discussion Overview

The discussion revolves around the use of generics in Java's ArrayList class, specifically the advantages of specifying a type (e.g., ArrayList) versus using a raw type (e.g., ArrayList). Participants also explore the implications of the default capacity of an ArrayList and when it might be beneficial to modify this capacity.

Discussion Character

  • Technical explanation
  • Conceptual clarification
  • Homework-related

Main Points Raised

  • Some participants argue that using generics (e.g., ArrayList) helps avoid the need for type checking and casting, making the code cleaner and less error-prone.
  • Others point out that using a raw ArrayList allows for more flexibility in terms of adding different object types, but this can lead to runtime errors and more complex code due to necessary type checks.
  • One participant explains that the default capacity of an ArrayList is 10, and changing this capacity can improve performance by reducing the number of times the list needs to be resized when adding elements.
  • Another participant provides a scenario where knowing the expected number of elements in advance could justify specifying a larger initial capacity to optimize memory usage.
  • A later reply discusses a practical coding scenario involving adding player objects to an ArrayList, clarifying that each new player object will occupy a new memory space and not replace previously added players.

Areas of Agreement / Disagreement

Participants generally agree on the benefits of using generics for type safety and clarity, but there are differing opinions on the necessity of modifying the default capacity of an ArrayList. The discussion about the behavior of the ArrayList when adding new objects remains unresolved, with participants providing insights without reaching a consensus.

Contextual Notes

Some assumptions about memory management and object references are discussed, but there is no detailed exploration of the underlying mechanics of Java's memory management or garbage collection processes.

Who May Find This Useful

This discussion may be useful for Java programming students, particularly those learning about collections and object-oriented programming concepts, as well as developers looking to understand best practices for using ArrayLists.

kirkulator
Messages
32
Reaction score
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
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:
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.
 
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?
 
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!
 

Similar threads

  • · Replies 1 ·
Replies
1
Views
1K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 10 ·
Replies
10
Views
12K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K