简体   繁体   English

搜索对象的数组列表

[英]Searching Array list of objects

I have an array list in a class the array is called realtorList.我在一个名为 realtorList 的类中有一个数组列表。 From my main class I store objects with realtor data to the realtorList.从我的主类,我将带有房地产经纪人数据的对象存储到房地产经纪人列表。 My data that is stored to a text file and is read in the first line.我的数据存储到文本文件并在第一行读取。 This is the first element in the realtorList after I store the first line of data.这是我存储第一行数据后 realtorList 中的第一个元素。

[Realtor{licenseNumber= AA1111111 , firstName=Anna, lastName=Astrid, phoneNumber=111-111-1111, commission=0.011}] [房地产经纪人{licenseNumber= AA1111111 , firstName=Anna, lastName=Astrid, phoneNumber=111-111-1111, Commission=0.011}]

When I read the next line of data from the input file I need to see if the licenseNumber in bold already exists in the realtorList.当我从输入文件中读取下一行数据时,我需要查看以粗体显示的 licenseNumber 是否已存在于 realtorList 中。 I am having trouble figuring out how to go about doing this.我无法弄清楚如何去做这件事。

For example if the next realtor data license number is AA1111111 how do I check the realtorList for AA1111111 which does exist for this example.例如,如果下一个房地产经纪人数据许可证编号是 AA1111111,我如何检查本示例中确实存在的 AA1111111 的房地产经纪人列表。

A really simple way to do this would be to have a String ArrayList running alongside (for example, one called licenses) and use an if statement with indexOf to return if that license value is already in the List.一个非常简单的方法是让一个 String ArrayList 并排运行(例如,一个称为 licenses 的),并使用带有 indexOf 的 if 语句来返回该许可证值是否已经在列表中。 Since the licenses ArrayList only has one value it can be easily searched with indexOf.由于许可证 ArrayList 只有一个值,因此可以使用 indexOf 轻松搜索。

An example would be一个例子是

private boolean checkLicense (String licenseNumber) {
        int i = licenses.indexOf(licenseNumber);
        if(i == -1) {
            return false;
        } else {
            return true;
        }
}

Similar code works in one of my projects where a dynamic List of motors for a robot checks to see if there's already a motor with the listed port before adding a new one.类似的代码在我的一个项目中起作用,其中机器人的动态电机列表在添加新电机之前检查是否已经有带有所列端口的电机。

Another method could use a for loop for a linear search such as另一种方法可以使用 for 循环进行线性搜索,例如

private boolean checkLicense (String licenseNumber) {
   for(int i = 0; i < (realtorList.size() - 1); i++) {
      if (licenseNumber.equals(realtorList[i].getLicenseNumber())) {
         return true;
      }
   }
   return false;
}

This would perform a linear search of each and every object until it finds it (it would need to be in a method like the one for the example above to work this way)这将对每个对象执行线性搜索,直到找到它(它需要使用类似于上面示例的方法才能以这种方式工作)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM