简体   繁体   English

在arrayList中找到一个特定的对象

[英]find a specific object in arrayList

I have a big arrayList filled with a file ( over 50000 line) and i need to find a specific object in this list 我有一个大的arrayList,里面充满了一个文件(超过50000行),我需要在此列表中找到特定的对象

My object class 我的物件类别

public class City{

    public City() {
        super();

    }
    private String name;
    private String department;


    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.nom = name;
    }
    public String getDepartment() {
        return deparement;
    }
    public void setDepartment(String department) {
        this.department = department;
    }

    @Override
    public String toString() {

        return name;
    }
}

A solution is doing 解决方案正在做

List<City> listCity = ParseFile.parseCityFile(this);
String item = textView.getText().toString();
                for (City c : listCity ) {
                    if(c.getName().equals(item))                                    
                        // stuff here
                }

but it's not receivable for obvious performance reasons. 但由于明显的性能原因,这是不可接受的。 Any advices for a better way to do this ? 有什么更好的方法建议吗?

Use a Map<String, City> instead of List<City> , use the City#name as the key in your map. 使用Map<String, City>代替List<City> ,使用City#name作为地图中的键。 If navigation order won't matter, then use HashMap as implementation, otherwise use LinkedHashMap or TreeMap . 如果导航顺序无关紧要,请使用HashMap作为实现,否则使用LinkedHashMapTreeMap

In your class City override equals() , hashCode() and Comparable - 在您的班级City重写equals()hashCode()Comparable

@Override
public boolean equals(Object b) {
  if (b != null) {
    if (this == b) return true;
    return this.getName().equals(((City) b).getName());
  }
  return false;
}

@Override
public int hashCode() {
  return this.getName().hashCode();
}

@Override
public int compareTo(City o) {
  return this.getName().compareTo(o);
}

Then you can use 那你可以用

if (listCity.contains(item)) {
}

And then for fast look-up you can use a Map, or a TreeSet . 然后,可以使用Map或TreeSet进行快速查找。 A TreeSet (per the Javadoc), TreeSet(根据Javadoc),

This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). 此实现为基本操作(添加,删除和包含)提供了保证的log(n)时间成本。

I'd use equals() method (add it to your City class): 我将使用equals()方法(将其添加到您的City类中):

public boolean equals(Object object) {
    boolean areEquals = false;
    if (object instanceof City) {
        City otherCity = (City) object;
        areEquals = (this.getName() == otherCity.getName() && this.getDepartment() == otherCity.getDepartment());
    }
    return areEquals;
}

And I'd also replace your if condition by: 我也将您的if条件替换为:

if (listCity.contains(item)) {
}

And that should do the trick! 那应该可以解决问题!

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

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