举一个简单的例子,考虑一个Place类:

public class Place {

    //fields
    private String name;

    private String state;

    private int population;

    private int squareMileage;

    private int elevation;

    //constructors
    public Place() {
    }

    public Place(String name, String state) {
        this.name = name;
        this.state = state;
    }

    public Place(String name, String state, int population, int squareMileage,
                    int elevation) {
        this.name = name;
        this.state = state;
        this.population = population;
        this.squareMileage = squareMileage;
        this.elevation = elevation;
    }

    //getters and setters
    public String getName() {
        return this.name;
    }

    public String getState() {
        return this.state;
    }
    //... (other getters and setters omitted)

    //do stuff
}


Places类(HashMap对象的Place):

import java.util.*;

public class Places {
    private Map searchablePlaces;

    public Places() {
        searchablePlaces = new HashMap();
    }

    public void add(Place value) {
        Place key = new Place(value.getName(), value.getState());
        searchablePlaces.put(key, value);
    }

    public Place find(Place key) {
        return searchablePlaces.get(key);
    }

    //override hashCode, equals

    //do stuff
}


本质上,我的问题是:


与直接在已排序的HashMap中搜索key相对,在value中搜索ArrayList会获得任何效率吗?
如果key的类型String等于name + state(或类型String[2])怎么办?

最佳答案

令人困惑,恕我直言。我将定义一个PlaceKey类,只包含一个名称和一个状态,并定义hashCode和equals。一个地方将保存一个PlaceKey和其他属性。我会使用Map<PlaceKey, Place>

请注意,在您的示例中,需要等号和hashCode的是Place类,而不是Places类。

现在,回答您的2个问题:


哈希映射为O(1),列表为O(n)。因此,映射通常会更快(可能只有非常小的n值除外)
串联几乎总是一个坏主意。您可能有name1 = aa,state1 = a,name2 = a和state2 = aa,这将导致冲突。数组不会就其内容覆盖equals和hashCode,因此它不是适当的映射键类。

10-06 11:09