-3
public class SecureSystem {
    final int low = 0;
    final int high = 1;
    HashMap<String, int[]> subject;
    HashMap<String, int[]> object;

    public SecureSystem() {
    subject = new HashMap<String, int[]>();
    object = new HashMap<String, int[]>();
    }
    ReferenceMonitor rm = new ReferenceMonitor();
    rm.ReferenceMonitor(subject,object);

    System.out.println(this.subject.get("a")); // how to make it print [1,2]?
    System.out.println(this.object.get("b")); // how to make it print [3,4]?
}
class ReferenceMonitor{
    ReferenceMonior(HashMap<String, int[]> subject, HashMap<String, int[]> object) {
        SecureSystem ss = new SecureSystem();
        ss.subject.put("a", new int{1,2});
        ss.object.put("a", new int{3,4})
    }
}

どうすればそれを行うことができますか?HashMaps を ReferenceMonitor クラスに渡してコンテンツを読み取ろうとすると、NullPointerError が返されます。

どうもありがとう。

4

3 に答える 3

0

問題はここにあります:

class ReferenceMonitor{
    ReferenceMonior(HashMap<String, int[]> subject, HashMap<String, int[]> object) {
        //these three lines are the culprit
        SecureSystem ss = new SecureSystem();
        ss.subject.put("a", new int{1,2});
        ss.object.put("a", new int{3,4})
    }
}

コンストラクター呼び出しの完了後に使用できなくなる新しいローカル変数内のsubjectandobjectマップにデータを入れています。とパラメータSecureSystem ssにデータを入れて、内容も変更されるようにする必要があります。subjectobject

class ReferenceMonitor{
    ReferenceMonior(HashMap<String, int[]> subject, HashMap<String, int[]> object) {
        //code fixed
        //also, there's no need to create a new SecureSystem instance
        subject.put("a", new int[] {1,2});
        object.put("b", new int[] {3,4});
    }
}

このコードは、代わりにオブジェクト参照を渡すように拡張することもできます。SecureSystem

class ReferenceMonitor{
    ReferenceMonior(SecureSystem secureSystem) {
        secureSystem.getSubject().put("a", new int[] {1,2});
        secureSystem.getObject().put("b", new int[] {3,4});
    }
}

また、 Java は参照渡しではないことに注意してください。

于 2013-09-13T22:44:19.937 に答える
0

HashMaps を初期化していません。作成したことがないため、null です。

HashMap<String, int[]> map = new HashMap<String, int[]>();

于 2013-09-13T21:31:54.500 に答える
-1

ハッシュマップを初期化するためにどこかで a を使用しましたnew()か? そうでない場合。あなたの答えがあります。

あなたが意図したのは次のようなものでした

class ReferenceMonitor{
    ReferenceMonior(HashMap<String, int[]> subject, HashMap<String, int[]> object) {
        SecureSystem ss = new SecureSystem();
        ss.subject=subject;
        ss.object=object;
        ss.subject.put("a", new int{1,2});
        ss.object.put("a", new int{3,4})
    }
}

その上、それはひどいコードです。

1)ビルダーパターンのようなパターンの使用を検討する必要があります

2) パブリック データ メンバーの使用は、OOP の情報隠蔽の原則に違反しており、悪いスタイルと見なされます。セッターメソッドを使用してください。

于 2013-09-13T21:32:23.980 に答える