0 java scope hashtable hashmap
对不起,这是代码有点长,但我需要得到正确的方案.
为什么这段代码输出全部'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());
}
}
Run Code Online (Sandbox Code Playgroud)
变化:
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);
Run Code Online (Sandbox Code Playgroud)
至
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);
Run Code Online (Sandbox Code Playgroud)
在第一段代码中,每次更新同一个对象
| 归档时间: |
|
| 查看次数: |
638 次 |
| 最近记录: |