?
Solved

How do I remove an object from an array.

Posted on 2003-03-17
28
Medium Priority
?
194 Views
Last Modified: 2010-03-31
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;
    }
  }
}
 
0
Comment
Question by:kgreenwoodusa
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 6
  • 5
  • +5
28 Comments
 
LVL 9

Expert Comment

by:yongsing
ID: 8150633
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;
   }
 }
}
0
 
LVL 9

Expert Comment

by:yongsing
ID: 8150653
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.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8150659
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.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 6

Expert Comment

by:expertmb
ID: 8150661
check for the null objects.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 8150689
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 :-)
0
 
LVL 15

Accepted Solution

by:
ozymandias earned 2000 total points
ID: 8150695
The code you ars using is not removing the student from the array it's just setting its reference to null, so you just end up with a null student in the array, which is not the same as removing it.

I would write an array resizing function that returns an array without the specified element.

public Student[] removeStudent(Student[] studentArray, String studentID){
    Vector v = new Vector();
    for (int i = 0; i < studentArray.length;i++){
        if (studentArray[i].getID() != studentID){
            v.add(studentArray[i]);
        }
    }
    Student[] newArray = Student[v.size];
    newArray = Student[])v.toArray(newArray);
    return newArray;
}

Then, to remove a student from your array you can call :

    students = removeStudent(students,aID);
0
 
LVL 9

Expert Comment

by:yongsing
ID: 8150823
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.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 8150863
> 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 ;-)
0
 
LVL 15

Expert Comment

by:ozymandias
ID: 8150864
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.
0
 
LVL 15

Expert Comment

by:ozymandias
ID: 8150874
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.
0
 
LVL 9

Expert Comment

by:yongsing
ID: 8150904
>> 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.
0
 
LVL 15

Expert Comment

by:ozymandias
ID: 8150922
>>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."
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8150934
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.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 8150938
> 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 ;-)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8150967
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();
}
0
 
LVL 35

Expert Comment

by:TimYates
ID: 8150995
It's amazing how 500 points and an easy question will get you so many different ways of doing things :-) >_< :-)
0
 
LVL 15

Expert Comment

by:ozymandias
ID: 8151022
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)
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8151023
CEHJ,

>> return (Student[])studentsAsList.toArray

????

Its: public void removeStudent (....)

Mayank.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8151046
Don't follow you. Am i missing something?
0
 
LVL 35

Expert Comment

by:TimYates
ID: 8151058
> 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*
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8151080
CEHJ,

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

Cheers,

Mayank.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8151105
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();
}
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8151127
Ya, that's all right, pal!

Mayank.
0
 
LVL 15

Expert Comment

by:ozymandias
ID: 8151191
Splitter !
If they take away the holy Vector I will start programming in Eiffel, and I shall take all my disciples with me !
0
 
LVL 1

Expert Comment

by:shji1
ID: 8151243
Why don't you just have a look at the Vector source code and learn from it a bit.
--
0
 

Author Comment

by:kgreenwoodusa
ID: 8151301
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.
0
 
LVL 15

Expert Comment

by:ozymandias
ID: 8151339
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)
0
 
LVL 35

Expert Comment

by:TimYates
ID: 8151556
Bah....Vectors suck a$$ ;-)

The church of copyArray shall avenge this defeat!

To the hills my friends!
0

Featured Post

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses
Course of the Month13 days, 21 hours left to enroll

800 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question