ArrayList 组 = 新的 ArrayList();
group.add("约翰·史密斯","5126123");
我想存储2个数据。所以我可以通过数字访问名称和通过名称访问数字。这可能与 ArrayList 以及如何?
*并且不同的人可以有相同的groupnumber
ArrayList 组 = 新的 ArrayList();
group.add("约翰·史密斯","5126123");
我想存储2个数据。所以我可以通过数字访问名称和通过名称访问数字。这可能与 ArrayList 以及如何?
*并且不同的人可以有相同的groupnumber
简单的解决方案(但可能不是最有效的):这不是在 IDE 中输入的,所以这里可能有错字。
公共类用户{
private int id;
private String name;
public User() {};
public User(int id, String name) {
this.id = id;
this.name = name;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
公共类 MyUserArray() {
private ArrayList<User> users;
public MyUserArray() {
users = new ArrayList<User>();
}
public add() {
users.add(user);
}
// Since you said the user name is unique, only
// one user will be returned
public User getUserByName(String name) {
for(User user : users) {
if(user.getName().equalsIgoreCase(name))
return user;
}
// return null if no user is found
return null;
}
// Since more users can have the same id, we will
// return an array list with results
public ArrayList<User> getUsersById(int id) {
ArrayList<User> result = new ArrayList<User>();
for(User user : users) {
if(user.getId() == id)
result.add(user);
}
return result;
}
}
公共类 MyClass {
public static void main(String[] args) {
// Create users
User user1 = new User(1, "John Doe");
User user2 = new User(1, "Jack Sparrow");
User user3 = new User(2, "Mickey Mouse");
// Create the personal user array
MyUserArray users = new MyUserArray();
// Add the users
users.add(user1);
users.add(user2);
users.add(user3);
// Now you can search on id:
ArrayList<User> userArrayList = users.getUsersById(1);
for (User user : userArrayList) {
System.out.println(user.getId() + " - " + user.getName());
// This will print:
// 1 - John Doe
// 1 - Jack Sparrow
}
// Or search on name
User user = users.getUserByName("Jack Sparrow");
System.out.println(user.getId() + " - " + user.getName());
// This will print: 1 - Jack Sparrow
}
}
您可以通过这种方式使用 ArrayList:-
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
Map<String, String> map1 = new HashMap<String, String>();
map1.put("John Smith","5126123");
list.add(map1);
或者您可以直接使用地图:-
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("Some String", 42);
// or, more correctly:
map.put("Some String", Integer.valueOf(42));
您可以使用搜索它
Integer result = map.get("Some String");
您可以像这样将数组存储在数组列表中
group.add(new String[][] {"John Smith", "5125123"});
但是,我不确定这对帮助您完成您想要完成的任何事情有多大用处。
另一种方法是使用哈希表或<key, value>
成对的映射/字典数据类型的其他一些实现。但是,搜索将仅限于使用密钥。
另一种选择是创建一个对象来保存 John Smith 及其相关信息,然后将该对象放入 arraylist 中。不过,您必须编写一些额外的代码来帮助您搜索和检索数据。