Comp Sci Why Use Generics in Java ArrayLists and Modify Default Capacity?

  • Thread starter Thread starter kirkulator
  • Start date Start date
  • Tags Tags
    Class Java
AI Thread Summary
Using generics in Java ArrayLists, such as ArrayList<String>, ensures type safety by allowing only specified object types, which prevents runtime errors and eliminates the need for casting. This approach simplifies code readability and maintenance, as developers can directly work with the intended data type without additional checks. Changing the default capacity of an ArrayList, which is 10, can enhance performance by reducing the overhead of resizing and copying elements when the list exceeds its initial size. If the expected number of elements is known in advance, initializing the ArrayList with a specific capacity can optimize memory usage. Overall, understanding these concepts is crucial for efficient Java programming and effective data management.
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
Views
1K
Replies
1
Views
2K
Replies
1
Views
1K
Replies
2
Views
1K
Replies
5
Views
3K
Replies
10
Views
11K
Replies
4
Views
1K
Replies
2
Views
1K
Back
Top