返回一个 HashMap 在 Java 中

huangapple go评论77阅读模式
英文:

Returning a HashMap in java

问题

我目前刚从Python转到Java,对于如何返回一个HashMap感到困惑,我尝试在网上搜索了几个小时,但没有找到解决我的问题的方法。以下是代码。

public HashMap<Integer, Character> dataset(String text) {
    HashMap<Integer, Character> dict = new HashMap<Integer, Character>(); // 将HashMap的创建移到循环外部

    for (int i = 0; i < text.length(); i++) {
        char value = text.charAt(i);
        dict.put(i, value);
        System.out.println(dict.getClass().getSimpleName());
    }
    
    return dict; // 将return语句放在循环之外
}

public static void main(String[] args) {
    // ... (你的main方法部分不变)
}

即使我仔细检查了要返回的变量是否为HashMap,这里还是有一个例外。

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
This method must return a result of type HashMap<Integer,Character>

我知道这可能是一个初学者的错误,但经过几个小时的研究,我没有找到有用的东西。

英文:

I am currently new to Java coming from Python, and I can't seem to figure out how to return a HashMap, I tried searching on the web for hours but couldnt find anything that would solve my problem.
Here's the code.

public HashMap&lt;Integer, Character&gt; dataset(String text) {
	for (int i = 0; i &lt; text.length(); i++) {
		char value = text.charAt(i);
		
		HashMap&lt;Integer, Character&gt; dict = new HashMap&lt;Integer, Character&gt;();
		dict.put(i,  value);
		System.out.println(dict.getClass().getSimpleName());

		return dict; // Here&#39;s the error
	}
}


public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	System.out.print(&quot;Enter text: &quot;);
	String text = sc.next();
	
	System.out.println(&quot;============================&quot;);
	
	System.out.println(&quot;1. Convert to uppercase&quot;);
	System.out.println(&quot;2. Conver to lowercase&quot;);
	System.out.println(&quot;3. Convert to a dataset&quot;);
	System.out.print(&quot;Enter selection:  &quot;);
	String choice = sc.next();
	
	StringConverter obj = new StringConverter();
	
	switch(choice) {
	case &quot;1&quot;:
		text = obj.upperCase(text);
		System.out.println(&quot;=====Converted to uppercase=====&quot;);
		System.out.println(text);
		break;
		
		
	case &quot;2&quot;:
		text = obj.lowerCase(text);
		System.out.println(&quot;=====Converted to lowercase=====&quot;);
		System.out.println(text);
		break;
		
	case &quot;3&quot;:
		obj.dataset(text);

		break;
		
	}
}

I even double checked to see if the variable i am returning is a HashMap or not.

here's the exception.

> Exception in thread "main" java.lang.Error: Unresolved compilation problem:
This method must return a result of type HashMap<Integer,Character>

I know this might be a rookie mistake but after hours of research I couldnt find anything helpful.

答案1

得分: 3

dict的定义和return语句移到循环外部,应该就可以了(dict的定义放在进入循环之前,return语句放在退出循环之后)。

在您当前的代码中,return语句不能保证可达(即如果循环甚至没有进入,则必须在非void函数中给出)。

此外,您的方法将在每次假设的迭代中调用return,这意味着您的方法将始终以第一次迭代结束。return会导致函数退出,无论之后发生什么,这意味着您的代码将无法按预期工作。另外,您会创建多个HashMaps,因为您在每次迭代中都调用构造函数。

public HashMap<Integer, Character> dataset(String text) {

    HashMap<Integer, Character> dict = new HashMap<Integer, Character>();

    for (int i = 0; i < text.length(); i++) {
        char value = text.charAt(i);
        dict.put(i,  value);
        System.out.println(dict.getClass().getSimpleName());
    }

    return dict; // 这是错误的地方
}
英文:

Move your definition of dict and your return statement out of the loop, and it should be fine (the first one before entering, the last one after exiting the loop).

In your current code, the return statement is not guaranteed to be reachable (i.e. if your loop is not even entered), which has to be given in a non-void function.

Additionally, your method would call return in each hypothetical iteration, which means your method will always end with the first iteration. A return leads to function exit, no matter what comes after, which means your code would not work as you'd expect. Additionally, you'd create multiple HashMaps, as you call the constructor once per iteration.

public HashMap&lt;Integer, Character&gt; dataset(String text) {

    HashMap&lt;Integer, Character&gt; dict = new HashMap&lt;Integer, Character&gt;();

    for (int i = 0; i &lt; text.length(); i++) {
        char value = text.charAt(i);
        dict.put(i,  value);
        System.out.println(dict.getClass().getSimpleName());
    }

    return dict; // Here&#39;s the error
}

huangapple
  • 本文由 发表于 2020年10月23日 21:46:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/64501202.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定