Results 1 to 4 of 4
- 10-15-2011, 06:39 AM #1
Member
- Join Date
- Sep 2011
- Posts
- 22
- Rep Power
- 0
I don't understand the code help!
static final int initCapacity = 5;
String array[];
int size;
public SimpleArrayList(){
array = new String[initCapacity];
size = 0;
}
public String get(int index){
return (String) array[index];
}
public void add(String value){
if (size == array.length)
addCapacity();
array[size] = value;
size++;
}
public void addCapacity(){
String arrayBigger[] = new String[array.length*2];
for(int i = 0; i < size; i++){
arrayBigger[i] = array[i];
}
array = arrayBigger;
}
public void delete(int index){
for(int i = index; i < size - 1; i++){ <How can this be? say size 3 and want to get 2nd one, int i = 2; i < 2 so it won't compile anyway.
array[i] = array[i + 1];
}
DON'T understand this 'delete' method please help!
size--; <I understand this part>
}
-
Re: I don't understand the code help!
The delete method simply goes to the index of the item that you want to delete, and shifts all items above it one down. So all the items remain in the array unchanged except for the one that you want deleted. It then reduces the size property of the class by one with size--. That's the same as size = size - 1;. While this method doesn't reduce the actual size of the array int array, by reducing size, you make it sort-of appear to be smaller to outside classes that use this class. Your comment about what happens if index = the size of the array -1 is correct. The array itself isn't changed but since size is reduced, the outside world (classes that use objects of this class) will think that the data held by this class is smaller by one item, that the last item has been removed.
- 10-15-2011, 07:02 AM #3
Member
- Join Date
- Sep 2011
- Posts
- 22
- Rep Power
- 0
Re: I don't understand the code help!
let's assume that the size is 4 and I want to delete the value in array[3]......... so this means that the actual value has not been removed just the size is reduced? hmm I cannot still understand because for example if there is an list of 2,3,4,5 if I want to delete index 1 then this is size of 4 and index of 2. so according to the code, in this case 4 wil replace 3 so 2,4,4,5 and then this will be 2,4,5,5? so again not removed? but just regard this as remove since the size will become 3 so that this only count 2,4,5?
-
Similar Threads
-
Trying to understand this code better
By Kimomaru in forum New To JavaReplies: 2Last Post: 09-28-2011, 10:44 PM -
Can any one help me to understand the Code
By soomroimran in forum New To JavaReplies: 2Last Post: 04-28-2011, 09:23 AM -
Understand Code
By Quizzle23 in forum New To JavaReplies: 9Last Post: 03-07-2011, 10:07 PM -
understand the code
By prof.deedee in forum New To JavaReplies: 8Last Post: 11-11-2009, 02:43 AM -
Trying to understand this code
By new2java2009 in forum New To JavaReplies: 2Last Post: 09-09-2009, 07:18 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks