繁体   English   中英

从方法获取哈希图

[英]get Hashmap from Method

我是Java的新手,还没有学习如何创建2个单独的类并将它们组合在一起,因此,我最终将所有内容都弄乱了,您可以想象代码最终看起来是无法理解的,我打算学习稍后在我的课程中。 但是,我需要一个可以与“方法”一起使用的解决方案,这样我的代码才能看起来更整洁,并且如果我需要对其进行添加或修复,也就不会很麻烦。

因此,基本上我的问题是我是否可以从主体使用Hashmap.get从方法中创建的哈希映射中获取信息:

static String createAccount(String username, String authpassword) {
    Map<String, String> newacc = new HashMap<String, String>();

}

上面是方法“看起来”的样子,下面是主要方法:

public static void main(String args[]) {
    newacc.get(username);

}

这可能吗,似乎我遇到了这个错误(我认为主要方法没有读取在方法中创建的hasmap。

error: cannot find symbol
    newacc.get(username);

先感谢您!

您的地图newacc将只能在createAccount方法中访问,而不能在外界访问,因为它的范围仅在createAccount方法中,因此编译错误。

若要解决此问题,请在类级别将newacc定义为静态。 因此,只需在方法之外定义Map即可:

static Map<String, String> newacc = new HashMap<String, String>();
static String createAccount(String username, String authpassword) {
    //access newacc here
}

同样,您可以直接在main方法中访问相同的对象。

您在createAccount()创建的映射被分配给局部变量newacc 这意味着您在方法完成后将丢失对它的引用。

如果要保留一个地图,可以在其中添加新帐户,可以将其设为班级的一个字段:

class AccountManager {
    private static Map<String, String> accounts = new HashMap<>();

    static void createAccount(String username, String authpassword) {
        accounts.put(username, authpassword);
    }

    static String getAuthPassword(String username) {
        return accounts.get(username);
    }

    public static void main(String[] args) {
        // get the input from somewhere
        AccountManager.createAccount(username, authpassword);
        AccountManager.getAuthPassword(username);
    }
}

您将无法使用当前代码从main方法访问newacc变量,因为newacc的作用域是createAccount方法。 您有两个选择,可以将newacc定义为类中的静态字段,并通过这两种方法访问相同的实例(请参阅@SMA的答案),或者从createAccount方法返回您的帐户并将其捕获到main 像这样:

Map<String, String> createAccount(String username, String password) {
    Map<String, String> newacc = new HashMap<String, String>();
    // do stuff with account

    return newacc;
}

public static void main(String[] args) {
    Map<String, String> newacc = createAccount("user", "pass");
    newacc.get("username");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM