【问题标题】:Get the index of array with known value of the structure获取结构已知值的数组索引
【发布时间】:2016-09-09 01:05:14
【问题描述】:

我的这个类有几个类似这样的属性:

public class FileIn {

public String id;

public void setID(String id_) {
    id = id_;
}

public String getID() {
    return id;
}

...

}

有 20 个属性。 然后我把这些数据放在一个 ArrayList 中:

public ArrayList<FileIn> dfor_A = new ArrayList<FileIn>();

好吧,稍后我需要获取一个元素的索引,但我知道 id

dfor_A.get(-unknow index-).getID();

如何搜索和获取索引?

【问题讨论】:

    标签: java arraylist multidimensional-array


    【解决方案1】:

    解决方案 1: 我认为你必须循环

    /*function perform operation dfor_A.indexOf(item.id);*/
    public int getIndexOf(String id,List dfor_A)
    {
       for (int i = 0; i < dfor_A.size(); i++) {
    
         FileIn fi = dfor_A.get (i);
         if (fi.getID().equals (id)) {
           return i;  // this is the index
         }
        }
    
        return -1;
    }
    

    解决方案 2: 如果您考虑它的良好性能。我建议你使用高级功能

    第 1 步:实现比较器

    public class FileInCustomComparator implements Comparator<FileIn> {
       @Override
       public int compare(FileIn fileIn1, FileIn fileIn2) {
          return fileIn1.getId()-fileIn2.getId();//id consider as int here
       }
    }
    

    第 2 步:对列表进行排序

    Collections.sort( for_A /*list here*/, new FileInCustomComparator());
    

    第 3 步:使用优化的内置算法搜索排序列表

    public void search(String key,List list) {
      System.out.println("\nSearching for " + key);
    
      int result = Collections.binarySearch(list, key);
      if (result >= 0)
         System.out.print(" Found at index " + result);
      else
         System.out.print(" Not found [" + result + "]");
    }
    

    【讨论】:

    • 很多项目看起来很慢。另外,由于您已经在循环,乳清不只是为索引保留counter?在您已经找到 indexOf 的项目时找到它会更慢。
    • 是的,循环是最后的资源,这将运行超过 5000 个项目,并且只获取 1 个值太浪费时间
    • 我先试过了,但是数据随着时间的变化和他的顺序是我无法控制的,所以如果一个项目在 3 或 4 小时后第一次运行时获得 x 索引它会改变,所以那不是一个选择。
    【解决方案2】:

    使用地图,例如哈希映射

    Map <String, FileIn> map = new HashMap <> ();
    map.put (fileIn.getID (), fileIn);
    

    稍后

    FileIn fileIn = map.get (fileIn.getID ());
    

    如果你真的想保留一个 ArrayList,那么你需要循环

    for (int i = 0; i < dfor_A.length; i++) {
    
        FileIn fi = dfor_A.get (i);
        if (fi.getID().equals (id)) {
           return i;  // this is the index
        }
    }
    

    【讨论】:

    • 如果可行,请考虑支持和/或接受我的回答
    • 是的,我赞成,但遗憾的是它不起作用。我必须弄清楚
    猜你喜欢
    • 1970-01-01
    • 2013-05-17
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    相关资源
    最近更新 更多