Search code examples
javacloneimmutability

clone immutable object in Java


i have an immutable object that has weight as int, in my code, i need to update the weight, inroder to do that, i need to make a copy of that object and set the weight with updated value. but the object doesn't have a clone() override, and i don't know which way is better, clone() or implement Cloneable interface?

here is my class:

public class WeightedEdge implements Edge {

    private final WeightedEdgeComparator _weightedEdgeComparator;

    private final Vertex _target;

    private final int _weight;

    WeightedEdge(Bundle bundle, Vertex target, int weight) {
        _weightedEdgeComparator = new EdgeComparator(bundle.getDirection());
        _target = target;
        _weight = weight;
    }

    @Override
    public Vertex target() {
        return _target;
    }

    @Override
    public int weight() {
        return _weight;
    }

        @Override
    public int compareTo(WeightedEdge o) {
        return _EdgeComparator.compare(this, o);
    }

    @Override
    public int hashCode() {...}

    @Override
    public boolean equals(Object obj) { ... }

    @Override
    public String toString() { ... }

Solution

  • How about just returning a new object with the new value:

    // as mentioned by AndrewBissell, there is no reference to the bundle
    // luckily, we only need the direction from the bundle :)
    private final int _direction;
    
    WeightedEdge(Bundle bundle, Vertex target, int weight) {
        this(bundle.getDirection(), target, weight);
    }
    
    WeightedEdge(int direction, Vertex target, int weight)
    {
        _direction = direction;
        _weightedEdgeComparator = new EdgeComparator(_direction);
        _target = target;
        _weight = weight;
    
    }
    
    WeightedEdge updatedObject(int newWeight)
    {
        return new WeightedEdge(_direction, _target, newWeight);
    }