简体   繁体   中英

How can I create pairs of objects in Java or organize my code

I'm programming a robot for my schools robotics club and need a way of organizing objects into pairs. The code uses two solenoid objects to represent one solenoid extending a retracting, I want to place these two objects into a 'pair' to keep track of, as I will be handling a lot of solenoid objects. Now coming from a long background of C++, I would use a struct for this, or even better the default STL pair. What kind of data structure should I use to organize pairs of objects? . I'm fairly new to Java, so I'm interested if there is anything better to use than just a class.

Note that in C++, you could just as easily use a class to represent a pair. Since Java only has classes, this is your only option. In other words, you can easily roll your own Pair class if you wish. You might even want a custom class which represents this pairing but also defines the exact interaction between the two objects in the pair.

Alternatively, you can use java.util.Map. This is especially useful if there is some sort of mapping semantics between the elements in a pair (ie the pair is ordered).

I think it's more than simply "keeping them together". If your solenoid pair has distinct behavior (one retracts, the other extends), I'd say you need a new type beyond Pair to implement that. It should be a custom type (eg SolenoidPair ) with the proper behavior.

If you wanted to roll your own Pair class:

public class Pair<X, Y> {

    private final X x;
    private final Y y;

    public Pair(X x, Y y) {
        this.x = x;
        this.y = y;
    }

    public X getX() {
        return x;
    }

    public Y getY() {
        return y;
    }
}

Used like:

Pair<String, Integer> p = new Pair<String, Integer>("Heloo", 100);

You may want to throw some setters in there too!

But it seems like that there would probably be a better way to go about encapsulating your data. It may be a better idea to wrap up more of you logic in this pair class and create a real object what some more refined and appropriate methods in.

考虑使用来自Apache Commons的Pair<L, R>

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