Link to home
Start Free TrialLog in
Avatar of kgreenwoodusa
kgreenwoodusa

asked on

How do I remove an object from an array.

Hi

I'm currently working on some code that uses an array object to store objects of type student.  Basically, an array of students.
I need to be able to remove a student from the array.  I know that the original code should have used the Vector class as it is a dynamic data structure but changing the storage object is not an option open to me.

I've tried this so far but it causes this error: java.lang.NullPointerException

private static final int STUDENT_NUMBER = 50;
private Student[] students;
students = new Student[STUDENT_NUMBER];
public void removeStudent(String aID)
{
  for (int i=0; i<students.length-1; i++)
  {
    if (students[i].getID().equalsIgnoreCase(aID))
    {
      students[i] = null;
    }
  }
}
 
Avatar of yongsing
yongsing

You should check whether an array element contains null:

public void removeStudent(String aID)
{
 for (int i=0; i<students.length; i++)
 {
   if (students[i] != null && (students[i].getID().equalsIgnoreCase(aID)))
   {
     students[i] = null;
   }
 }
}
Also, notice in the for loop, I changed:

for (int i=0; i<students.length-1; i++)

to

for (int i=0; i<students.length; i++)

In your original for loop, you will miss out on the last element in the array.
Avatar of Mayank S
If you want to delete an element from the array, then keep a counter and move all the elements ahead of the element to be deleted one position back, like:

// count is an integer holding the number of elements in the students array currently

for (int i = 0 ; i < count ; i ++ )
{
  if ( students[i].getID().equalsIgnoreCase ( aID ) )
    for ( int j = i ; j < count - 1 ; j ++ )
    {
      students[j].id = students[j+1].id ;
     
      // sameway, copy other data members
     
      count -- ; // since one element was removed
      break ;

    } // end nested for, if

} // end outer for


Hope that helps!

Mayank.
check for the null objects.
public void removeStudent(String aID)
{
 for( int i = students.length - 1 ; i >= 0 ; i-- )
 {
   if (students[i].getID().equalsIgnoreCase(aID))
   {
     Student[] temp = new Student[ students.length ] ;
     System.arrayCopy( students, 0, temp, 0, students.length ) ;
     students = new Student[ temp.length - 1 ] ;
     if( i > 0 )
       System.arrayCopy( temp, 0, students, 0, i - 1 ) ;
     if( i < students.length - 1 )
       System.arrayCopy( temp, i + 1, students, i, temp.length - i + 1 ) ;
   }
 }
}

or something :-)
ASKER CERTIFIED SOLUTION
Avatar of ozymandias
ozymandias
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You guys are coming up with codes for resizing the array, but are making the same mistake as the questioner: if one of the array element is null, your code will throw NullPointerException.
> You guys are coming up with codes for resizing the array, but are making the same mistake as the questioner: if one of the array element is null, your code will throw NullPointerException.

Mine wont...  Nor will ozymandias'

Havent checked the others ;-)
No. The point that null student objects should be checked for has already been made several times. I'm not going to repeat it unecessarily. The point is that "removing" an element from an array implies "resizing" it. If you remove something from a collection the collection becomes smaller. That is not the same as setting it to null.

The original question implies that the asker wants to resize the array since they state that it would have been better to use a Vector.
Actually Tim, I think my code would throw a NullPointer exception because I call getID() on every element in the student array without checking that it is not null.

My line of code should be :

    if ((studentArray[i] != null) && (studentArray[i].getID() != studentID)){


But since the point had been made already I didn't bother.
>> Mine wont...  Nor will ozymandias'

Are you sure? The following line will throw NullPointerException if students[i] is null.

if (students[i].getID().equalsIgnoreCase(aID))


>> The original question implies that the asker wants to resize the array since they state that it would have been better to use a Vector.

My interpretation is that he is asking why he is getting NullPointerException.
>>My interpretation is that he is asking why he is getting NullPointerException.

OK. Your interpretation is different from mine.
If that really is the question and the code posted really is the code then the answer is, "you are getting a null pointer exception because all your students are null. None of them are instantiated. The array is an array of 50 null students."
He is getting the null-pointer exception because he is setting the object to be deleted to a null and leaving it in the middle of the array just like that. Now in case he scans the array in another loop and tries to read the ID or any other data member, then he will get a null-pointer exception when he tries to access the data-member for that null object. That's why I asked him to shift all the elements back and keep updating a counter for the number of elements.

Cheers :-)

Mayank.
> Are you sure? The following line will throw NullPointerException if students[i] is null.

> if (students[i].getID().equalsIgnoreCase(aID))

Yes, but in my code, I remove the element, and don't set it to null, so this state never occurs :-)

I think ;-)
OK, you have used an array, and, as you say, it would have been better to use a collection class of some sort. But this doesn't prevent you using some of those classes to move between arrays and collections. You can do something like the following, after importing java.util.*:

public void removeStudent(Student[] students, String aID)
{
  List studentsAsList = Arrays.asList(students);
  Iterator iter = studentsAsList.iterator();
  while (iter.hasNext())
  {
    Student student = (Student)iter.next();
    if student.getID().equalsIgnoreCase(aID))
    {
      iter.remove();
    }
  }
  return (Student[])studentsAsList.toArray();
}
It's amazing how 500 points and an easy question will get you so many different ways of doing things :-) >_< :-)
Yes Tim, what's more I think we could probably work this up into a raging flame war by the time kgreenwoodusa comes back to read the comments. What say you, people ? I would like to declare my fanatical devotion to a Vector-based solution which will undoubteldy triumph over CEHJ's heretical usage of the unholy List and Interator model :0)
CEHJ,

>> return (Student[])studentsAsList.toArray

????

Its: public void removeStudent (....)

Mayank.
Don't follow you. Am i missing something?
> I would like to declare my fanatical devotion to a Vector-based solution which will undoubteldy triumph over CEHJ's heretical usage of the unholy List and Interator model :0)

I demand that we use arrayCopy!!  All who don't agree are fools ;-)  I heard that Vector is going to be phased out anyway ;-) ;-) ;-)  *giggle*
CEHJ,

The return type you specified is void. How can you return something then? That's all.

Cheers,

Mayank.
Doh! Well spotted. Should be :

public Student[] removeStudent(Student[] students, String aID)
{
 List studentsAsList = Arrays.asList(students);
 Iterator iter = studentsAsList.iterator();
 while (iter.hasNext())
 {
   Student student = (Student)iter.next();
   if student.getID().equalsIgnoreCase(aID))
   {
     iter.remove();
   }
 }
 return (Student[])studentsAsList.toArray();
}
Ya, that's all right, pal!

Mayank.
Splitter !
If they take away the holy Vector I will start programming in Eiffel, and I shall take all my disciples with me !
Why don't you just have a look at the Vector source code and learn from it a bit.
--
Avatar of kgreenwoodusa

ASKER

Guys,

Thanks for all the suggestions.  It was amazing how much interest 500 points can attract.  

I like ozymandias's solution the best as I did want to resize the array, perhaps I should of made that a bit clearer in the question. Sorry.

Anyway, the code works fine so thanks a lot.

Looking forward to the next time I need a question answering.  

The Java student.
My pleasure.
The Holy Church of Ozymandias the Vectorite welcomes you with open arms. Please send us all your money, shave your head and wait for the spaceships in your orange pyjamas and tinfoil helmet :0)
Bah....Vectors suck a$$ ;-)

The church of copyArray shall avenge this defeat!

To the hills my friends!