I’m stuck on a homework question… so far, using Arrays ONLY I’m having trouble deleting an object in an array by setting it to a null object..I had 3 methods, one method to add an object, one method to return a specific object from an array, one method to delete..so far the add and return objects methods work..but not the delete method…some help guys??
this is the class for the arrays and methods…I’m testing the methods in a main method
public class Book {
public void addContact(Contact[] contactBook)
{
int slots = 0;
for(Contact i : contactBook)
if (i == null)
slots++;
if(slots == 0)
System.out.println("Contact book full..can't add anymore!");
else
{
String name = Keyboard.readString("Enter name: ");
int id = Keyboard.readInt("Enter "+name+"'s id: ");
String classroom = Keyboard.readString("Enter "+name+"'s class: ");
int number = Keyboard.readInt("Enter "+name+"'s mobile: ");
for (int i = 0; i < contactBook.length; i++)
{
if(contactBook[i] == null){
contactBook[i] = new Contact(name,id,number,classroom);
break;
}
}
}//end else
}//end method
public Contact getContact(Contact[] contactList)
{
Contact contact = null;
int id = Keyboard.readInt("Enter student id: ");
try
{
for(Contact i : contactList)
{
if(i.id == id)
{
contact =i;
break;
}
}
}
catch(NullPointerException e)
{
System.out.println("Student ID:"+id+" does not exist..");
}
return contact;
}//end getContact
public void deleteContact(Contact[] contactList)
{
Contact delete = getContact(contactList);
for(Contact i : contactList)
{
if(i!=null)
if(delete.id == i.id)
{
i = null;
break;
}
}
}//end delete
public static void main(String args[])
{
Contact[] contacts = new Contact[200];
Book newBook = new Book();
newBook.addContact(contacts);
for (Contact i : contacts)
if(i != null)
System.out.println(i);
newBook.deleteContact(contacts);
for (Contact i : contacts)
if(i != null)
System.out.println(i);
}
}
this is the class of the object
public class Contact {
String name;
String classroom;
int id;
int number;
Contact(String name, int id, int number,String classroom)
{
this.name = name;
this.id = id;
this.number = number;
this.classroom = classroom;
}
public String toString()
{
return ""+name+", student id: "+id+" class:"+classroom+" mobile:"+number;
}
}
The iterator does return a copy of the reference to the Contact object. You are setting this copy to null and not the object that is stored in the array.
Use something like this: