gpt4 book ai didi

java - java中的哈希表给了我最后存储的值,但不是正确的值

转载 作者:行者123 更新时间:2023-12-01 07:00:01 26 4
gpt4 key购买 nike

抱歉,代码有点长,但我需要获得正确的场景。

为什么此代码输出所有 'C'

import java.util.Hashtable;

public class Main {
public static ContainsTheHash containsthehash = new ContainsTheHash();
public static StoresValues storesvalues = new StoresValues();
public static GetsValuesAndPrints getsvaluesandprints = new GetsValuesAndPrints();
public static void main(String[] args) {}

}

class ContainsTheHash {

Hashtable script_code = new Hashtable();
public Contains_The_Hash() {};
public void put(long key, Script_Hash_Type sht){script_code.put(key, sht);}
public ScriptHashType get(long key){return (Script_Hash_Type)script_code.get(key);}

}

class ScriptHashType {

String string;
public ScriptHashType(){}
public String getstring () {return string;}
public void setstring(String str){string = str;}

}



class StoresValues {

public StoresValues(){
put();
}
public void put(){


ScriptHashType sht = new ScriptHashType();
sht.setstring("A");
Main.contains_the_hash.put(1,sht);
sht.setstring("B");
Main.contains_the_hash.put(2,sht);
sht.setstring("C");
Main.contains_the_hash.put(3,sht);
}

}

class GetsValuesAndPrints {

public GetsValuesAndPrints(){

//should print "A\n B\n C\n"
long temp = 1;
System.out.println(get(temp));
temp = 2;
System.out.println(get(temp));
temp = 3;
System.out.println(get(temp));
};


public String get(long key){

return new String(((Script_Hash_Type)Main.contains_the_hash.get(key)).getstring());

}
}

最佳答案

更改:

ScriptHashType sht = new ScriptHashType();
sht.setstring("A");
Main.contains_the_hash.put(1,sht);
sht.setstring("B");
Main.contains_the_hash.put(2,sht);
sht.setstring("C");
Main.contains_the_hash.put(3,sht);

ScriptHashType sht = new ScriptHashType();
sht.setstring("A");
Main.contains_the_hash.put(1,sht);
sht = new ScriptHashType();
sht.setstring("B");
Main.contains_the_hash.put(2,sht);
sht = new ScriptHashType();
sht.setstring("C");
Main.contains_the_hash.put(3,sht);

在第一段代码中,您每次都更新同一个对象

关于java - java中的哈希表给了我最后存储的值,但不是正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1293945/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com