我遇到了一个家庭作业问题...到目前为止,仅使用数组我通过将其设置为空对象来删除数组中的对象时遇到问题。我有3个方法,一个方法来添加一个对象,一个从数组返回特定对象的方法,一个删除方法。到目前为止,添加和返回对象方法工作..但不是删除方法...一些帮助人?
这是数组和方法的类......我正在测试main方法中的方法
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);
}
}
这是对象的类 公共课程联系{
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;
}
}
答案 0 :(得分:3)
迭代器确实返回对Contact对象的引用的副本。您将此副本设置为null,而不是存储在数组中的对象。
使用类似的东西:
for(int i=0; i<contactList.size; i++) {
if(delete.id == contactList[i].id) {
contactList[i] = null;
break;
}
}
答案 1 :(得分:2)
我认为你不能以这种方式使用增强的for循环。你应该只使用一个普通的for循环来做contactList[i] = null
,其中i是索引。这是一些guidelines
for-each适合的地方 虽然增强的for循环可以使代码更清晰,但它不能在某些常见情况下使用。