• Post Reply Bookmark Topic Watch Topic
  • New Topic

Comparing ArrayList to a regular array  RSS feed

 
Arun raghvan
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
After 2 days ...i was able to enter 6th chapter

well as per the comparison Array needs an index to assign when assignment is above the length it blows up at runtime...



AS per book

gives a same runtime error .


although you can give it a size you want too where should we enter the size if that is the case!?.

head first java:page 137 ,Comparing ArrayList to a regular array
 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
After you have read the javadoc what do you think has gone wrong?
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Arun raghvan wrote:

AS per book

gives a same runtime error .


although you can give it a size you want too where should we enter the size if that is the case!?.


That is badly worded. You can give an ArrayList a capacity, but not a size.

The size of an ArrayList is the number of objects it currently contains. The capacity of an Arraylist is the number of objects that can be added to it without having to resize the array that is actually holding the objects in the background.

Sowill give you an ArrayList with a capacity of 2 but a size of 0.

will make the size 1 but leave the capacity at 2.
myList.add("string 2");
myList.add("string 3");
will make the size 3 and the capacity at least 3.

With regard to the add method that takes two parameters - the first is the position in the Arraylist where you want to insert the object. If the value of this parameter is larger than the current size of the ArrayList, there are two things this method could do.

1. Insert null references in the ArrayList until it is big enough to insert the object at the required position.
2. Throw an exception.

The Java developers chose to do the second, so if you want to add an object at position 1 of an empty ArrayList you first need to add a null reference at position 0.

The reason for choosing the second option is probably because the add(int, Object) method is part of the List interface and some implementations do not allow null references to be added.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!