抱歉,这段代码很长,但是我需要获得正确的方案。

为什么此代码输出所有'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);


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

09-27 23:23