很抱歉这是代码有点长,但我需要得到正确的方案。
为什么此代码输出所有'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());
}
}
答案 0 :(得分:6)
更改:
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);
在第一段代码中,每次更新同一个对象
答案 1 :(得分:3)
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);
}
使用new运算符只构建一个单个对象sht。您添加该对象3次。该对象上的最后一个设置字符串将字符串设置为“C”。因为只有一个对象sht,单个对象将具有值“C”。
你应该做的是:
public void put() {
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);
}
答案 2 :(得分:0)
您只是将一个ScriptHashType实例存储到Hashtable中,然后操纵其值。要获得您期望的行为,您需要创建三个ScriptHashType实例,每个实例用于一个所需的值。