简体   繁体   中英

How do I retrieve a value from two objects in Java?

I want to do something like the following:

MyObject obj1 = new MyObject();
MyObject obj2 = new MyObject();
MyObject obj3 = new MyObject();
MyObject obj4 = new MyObject();

values[obj1][obj2] = 1;
values[obj2][obj4] = 2;
values[obj1][obj4] = 3;

int someValue = values[obj1][obj2];
int someOtherValue = values[obj2][obj4];
int anotherValue = values[obj1][obj4];

How do I create these getter and setters with two objects as the key in Java?

The syntax in your question looks more like C#, and is not valid in Java, where array indices must be integers.

You can create a Pair<F,S> class that contains references to two objects.

Then you can create a HashMap<Pair<MyObject,MyObject>,Integer> , so a Pair of MyObject instances would serve as the key.

Map<Pair<MyObject,MyObject>,Integer> values = new HashMap<>();

Then you'll assign values with:

values.put(new Pair<>(obj1,ob2), 1);

and get the value with:

Integer someValue = values.get(new Pair<>(obj1,ob2));

You'll have to properly override equals and hashCode is both the Pair class and the MyObject class.

You can Use another Class to return the Two Object.. may be you can work around this

    final class MyResultObject {
            private final MyObject firstObject;
            private final MyObject secondObject;
        private final int key;
            public MyResult(MyObject firstObject, MyObject secondObject ,int key) {
                this.firstObject = firstObject;
                this.secondObject = secondObject;
                this.key=key;
            }


    public int getKey() {
                return key;
            }
    Public int getKeyValue(MyObject Object1, MyObject Object2){

}
        }

       //and then you can workaround this
        public static void main(String[] args) {
            MyResultObject resultOb = new MyResultObject(obj1,obj2,1);
            System.out.println(resultOb.getFirstObject() + resultOb.getSecondOBject());
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM