改造user ,使得userId相同视为一个对象,user是Key,User的username做value

如果您想要将具有相同userId的用户视为一个对象,其中User对象是键,而User对象的username是值,您可以使用Java的Map数据结构来实现。以下是示例代码:

 
  

java

import java.util.*;

class User {
    private int userId;
    private String username;

    public User(int userId, String username) {
        this.userId = userId;
        this.username = username;
    }

    public int getUserId() {
        return userId;
    }

    public String getUsername() {
        return username;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return userId == user.userId;
    }

    @Override
    public int hashCode() {
        return Objects.hash(userId);
    }
}

public class UserManagement {
    public static void main(String[] args) {
        Map userMap = new HashMap<>();

        User user1 = new User(1, "User One");
        User user2 = new User(2, "User Two");
        User user3 = new User(1, "User Three"); // 具有相同的userId

        userMap.put(user1, user1.getUsername());
        userMap.put(user2, user2.getUsername());
        userMap.put(user3, user3.getUsername()); // 相同的User对象会被覆盖

        // 打印所有用户及其username
        for (Map.Entry entry : userMap.entrySet()) {
            System.out.println("User ID: " + entry.getKey().getUserId() + ", Username: " + entry.getValue());
        }
    }
}

你可能感兴趣的:(java)