java 如何从数组中检索数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30499023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:13:53  来源:igfitidea点击:

How to retrieve data from array?

javaarrays

提问by iReaperx

I am writing a program for a hotel booking system. I currently have the room info in an array and I wish the customer to enter the ID of the room and it will retrieve all the details for that certain room. Here is the code for the array:

我正在为酒店预订系统编写程序。我目前有一个数组中的房间信息,我希望客户输入房间的 ID,它会检索该特定房间的所有详细信息。这是数组的代码:

  Room [] rooms = 
  {
    new Room("GARDEN0001", "NorthWest Garden View", 45.00),
    new Room("GARDEN0002", "SouthEast Garden View", 65.0),
    new Room("GARDEN0003", "North Garden View", 35.00),
    new Room("GARDEN0004", "South Garden View", 52.0),
    new Room("GARDEN0005", "West Garden View", 35.00),
    new Room("GARDEN0006", "East Garden View", 35.00)      
  };

The format is ID, Description, Price.

格式为 ID、描述、价格。

Thanks in advance

提前致谢

回答by amit

You can iterate the array with a for-each loop, and check if it matches:

您可以使用 for-each 循环迭代数组,并检查它是否匹配:

for (Room r : rooms) { 
    if (r.id.equals(REQUESTED_ID)) {
           //do something with it
    }
}

However, if your array grows large, you might want to switch to a smarter data structure such as a HashSet, that allows smart (and quick) searches.
Note you will also need to override Room#equals()and Room#hashCode()in order to use a HashSet, or similarly a HashMap<String,Room>

但是,如果您的数组变大,您可能希望切换到更智能的数据结构,例如HashSet,它允许智能(和快速)搜索。
请注意,您还需要覆盖Room#equals()andRoom#hashCode()以使用 aHashSet或类似的 aHashMap<String,Room>

回答by Soumitri Pattnaik

You can access/retrieve the items of an array by it's indexes.

您可以通过它的indexes.

Let's say :

让我们说:

int[] x = new int[5];
x[2] = 4; // Access the 3rd element

The first element's index always starts from 0, and it's called base index.

第一个元素的索引总是从 开始0,它被称为base index

So if the size of the array is 3, then all the element's indexes are 0,1,2.

所以如果数组的大小是 3,那么所有元素的索引都是 0,1,2。

In this case, you can access the items :

在这种情况下,您可以访问项目:

for(int i = 0 ; i < rooms.length ; i ++) {
    if(room.getID().equals(userInput)){
    //
    }
}

OR

或者

for(Room room : rooms) {
   // access by room. , here room is you item
   if(room.getID().equals(userInput)){
    //
   }
}

回答by Kitalda

Although you can do as in amit's answer, and iterate through them, I strongly suggest you to use some form of Map. That is what they are made for.

尽管您可以按照amit的回答进行操作并遍历它们,但我强烈建议您使用某种形式的 Map。这就是他们的目的。

Map<String, Room> rooms = new HashMap<>();
Room r = new Room("GARDEN0001", "NorthWest Garden View", 45.00);
rooms.put(r.getId(), r);
r = new Room("GARDEN0002", "SouthEast Garden View", 65.0);
rooms.put(r.getId(), r);
r = new Room("GARDEN0003", "North Garden View", 35.00);
rooms.put(r.getId(), r);
r = new Room("GARDEN0004", "South Garden View", 52.0);
rooms.put(r.getId(), r);
r = new Room("GARDEN0005", "West Garden View", 35.00);
rooms.put(r.getId(), r);
r = new Room("GARDEN0006", "East Garden View", 35.00);
rooms.put(r.getId(), r);

(I'm assuming your Roomclass has a getId()method that returns the id.) You can then retrieve rooms as this:

(我假设你的Room类有一个getId()返回 id的方法。)然后你可以这样检索房间:

Room room = rooms.get("GARDENOOO2");

or

或者

Room room = rooms.get(savedId);

回答by Vlad Dmitriev

If you are using java8, you can do it this way:

如果您使用的是 java8,您可以这样做:

Arrays.stream(rooms).filter(room -> "YOUR_ID".equals(room.getId())).findFirst().get();

回答by KernelKoder

Arrays are accessed by index. There is no way to directly get the Roomby ID. You could loop through the roomsand select the correct Roomas follows:

数组通过索引访问。没有办法直接得到Roomby ID。您可以循环遍历rooms并选择正确的Room,如下所示:

private Room getRoomById(String id) {
    for (Object room : rooms) {
        if (room.getId == id) {
            return room;
        }
    }
    return null;
}

回答by Hector

Array is the wrong tool for the job. What you have done is give yourself a harder problem than you needed to. I would recommend using a TreeMap to store unique room ids as key (Java String have correct implementations of equals, hashcode and compareTo methods), and refactored Room instances as values.

Array 是错误的工作工具。你所做的是给自己一个比你需要的更难的问题。我建议使用 TreeMap 将唯一的房间 ID 存储为键(Java String 具有 equals、hashcode 和 compareTo 方法的正确实现),并将 Room 实例重构为值。

Change your Room value object by removing the key field then store it as the TreeMap value, using the room id (in a Java String) as the TreeMap key.

通过删除键字段更改 Room 值对象,然后将其存储为 TreeMap 值,使用房间 ID(在 Java 字符串中)作为 TreeMap 键。

By employing a TreeMap theres no need to loop through the stored rooms, you can use the TreeMaps get(Object key) method to retrieve the required room details.

通过使用 TreeMap 无需遍历存储的房间,您可以使用 TreeMaps get(Object key) 方法来检索所需的房间详细信息。

回答by Ninad Pingale

Here is some code just to give you idea.

这里有一些代码只是为了给你想法。

for(Room room:rooms ){
if(room.getID().equals(userInput)){
 return room;
}
}