在不知道对象变量的情况下从arraylist中查找和删除对象

时间:2016-04-07 10:16:00

标签: java arraylist

我是Java的新手,我一直在抨击墙壁以解决这个问题。无论如何,下面是一个创建Person的类,在它下面,是一个使用Person类型Phonebook创建ArrayList的类。我想编写删除函数(为了从列表中删除Person),但我的问题是,因为我只得到了我不能使用Indexof函数的人的名字(因为它需要对象)得到这个名字的位置。

这是我第一次使用ArrayList存储对象,所以我甚至不确定  我的结果会如何显示。我猜测,如果名称(在我的列表中)的位置是10,则11将是电话,12将是地址。我是对的吗?

public class Person
    {
       private String name;
       private String phone;
       private String address;

public Person (String n, String p, String a)
{
     this.name = n;
     this.phone = p;
     this.address = a;
}

public void setPhone(String newPhone)
{
   this.phone = newPhone;
}

public String getName()
{
     return this.name;
}

public String getPhone()
{
      return this.phone;
}

public String getAddress()
{
      return this.address;
}



public String print()
{
      return "Name is : " + this.name + "\nPhone is : " + this.phone + "\nAddress is : " + this.address;
}

}

import java.util.*;

public class phoneBook
{
            Scanner in = new Scanner ( System.in );
            private ArrayList <Person> persons = new ArrayList <Person>();
            private int i;
            private boolean flag;


        public void addPerson(Person p)
        {
            persons.add(p);
        }

        public void listPersons () 
        {
            System.out.println(persons);
        }

        public void lookUp (String theName) 
        {
            flag = persons.contains(theName);
            if ( flag == true )
            {
                System.out.println("That name exists!");
            }
            else
            {
                System.out.println("That name does not exist!");
            }
        }

        public void remove (String theName) 
        {

        }

编辑:我打算在其他功能中使用扫描仪。别担心。

3 个答案:

答案 0 :(得分:0)

I'm not sure of if do you want to get the object of that array, but each object is indexed to that array (with full attributes), now you can remove it by using the following code,

public String removePerson(ArrayList<Person> arrayList,String name)
{
 for(Person currentPerson:arrayList)
 {
     if(currentPerson.getName().equals(name))
     {
         arrayList.remove(currentPerson);
         return "Removed successfully"
     }
 }
 return "No record found for that person";
}

just pass the arrayList and the name of that person to this method

答案 1 :(得分:0)

You should override the equals() and hashCode() methods in the Person class. This way you will define when two objects of this type will be considered equal. Then you can use list.contains(yourObject) to determine if that object is equal to any object in your list, this based on your equals() implementation.

答案 2 :(得分:0)

Does this help you?

   public void remove (String theName,ArrayList<Person> persons)   {

       for (int i = 0; i < persons.size();++i) {

           if(persons[i].getName().equals(theName)) {

              persons.remove(i);
           }
      }   
   }

Best regards, Nazar