gpt4 book ai didi

java - 有效地查找对象数组中的元素

转载 作者:行者123 更新时间:2023-12-02 06:06:02 26 4
gpt4 key购买 nike

我有一个很长的对象数组:

public static class __Location {
public __Location(int locationId, String locationDesc) {
this.LocationId = locationId;
this.LocationDesc = locationDesc;
}

public int LocationId;
public String LocationDesc;
}


public static __Location[] LOCATIONS = { new __Location(100, "Afghanistan"), new __Location(110, "Albania"), new __Location(120, "Algeria"),
new __Location(130, "American Samoa"), new __Location(140, "Andorra"), new __Location(150, "Angola"), new __Location(160, "Anguilla"),
new __Location(170, "Antarctica"), new __Location(180, "Antigua And Barbuda"), new __Location(190, "Argentina"), new __Location(200, "Armenia"),
new __Location(210, "Aruba"), new __Location(220, "Australia"), new __Location(230, "Austria"), new __Location(240, "Azerbaijan"),
new __Location(250, "Bahamas"), new __Location(260, "Bahrain"), new __Location(270, "Bangladesh"), new __Location(280, "Barbados"),
new __Location(290, "Belarus"), new __Location(300, "Belgium"), new __Location(310, "Belize"), new __Location(320, "Benin"),
new __Location(330, "Bermuda"), new __Location(340, "Bhutan"), new __Location(350, "Bolivia"), new __Location(360, "Bosnia And Herzegovina"),
new __Location(370, "Botswana"), new __Location(380, "Bouvet Island"), new __Location(390, "Brazil"),
new __Location(400, "British Indian Ocean Territory"), ...

我的问题是如何在这个长数组中有效地搜索某个项目(根据其键值,即 LocationId)。

最佳答案

使用HashMap可以高效地访问item,时间复杂度为O(1):

Map<Integer, __Location> map = new HashMap<Integer, __Location>();

这个HashMapkeyLocationIdvalue是对应的__Location对象.

关于java - 有效地查找对象数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22286421/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com