问题描述
|
我正在考虑一种在Java中查找成员ID的方法。但是我首先需要知道是否可以将这些ID分组存储。
问题是我希望成员ID = FirstName,LastName;
如何将它们一起存储?
ID将是一个整数,但名称将是一个字符串。
就像如果查找会员id> 433 ||我要输出> Smith,John
我还希望能够搜索Smith的名称并获得> 433,Smith,John
如何创建一个变量来存储这些变量,以便它们像这样链接在一起?
我不知道这叫什么,否则我会自己查一下。有人知道我可以在哪里开始研究吗?
解决方法
您想将相关值分组为一个类,例如:
public class Person {
private final int id;
private final String firstName;
private final String lastName;
public Person(int id,String firstName,String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public int getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
@Override
public String toString() {
return String.valueOf(id) + \",\" + firstName + \",\" + lastName;
}
}
然后,使用地图搜索您的值:
public static void main(String[] args) {
Map<Integer,Person> persons = new HashMap<Integer,Person>();
persons.put(433,new Person(433,\"John\",\"Smith\");
System.out.println(persons.get(433).toString());
// The output for this is 433,John,Smith
}
, 我想您正在寻找BiMap之类的东西。
它基本上是一个HashMap,同时将key
映射到value
和value
映射到key
。
这是标准地图(仅在一个方向上起作用)的示例:
HashMap<Integer,String> yourMap = new HashMap<Integer,String>()
yourMap.put(433,\"FirstName,LastName\"); // associate key \"433\" with \"FirstName,LastName\"
System.out.println(yourMap.get(433)); // will print \"FirstName,LastName\"
, 使用Map
,并以Map.Entry<String,String>
作为值。
Map<Integer,Map.Entry<String,String>> members = new HashMap<Integer,String>>();
members.put(123,new AbstractMap.SimpleEntry<String,String>(\"John\",\"Doe\"));
members.get(123).getKey(); //returns John
members.get(123).getValue(); //returns Doe