Rod
Rod

Reputation: 464

Ordering objects by an attribute of a generic attribute

Say that I have this class:

public class Bucket<T> {
        T filling;
}

and the filling attribute can be an instance of either one of these:

public class Oil{
    float volume;
}

or

public class Water{
    float volume;
}

In one part of my code, I have a list of Buckets:

LinkedList<Bucket> list;

Now, I want to order the elements of "list"(Bucket) by the attribute "volume". But I can't compare T.volume. So, how do I do that?

Sorry in advance if my question is stupid, I'm still learning java.

Upvotes: 0

Views: 61

Answers (1)

Happy
Happy

Reputation: 1865

I answer you assuming this is a theoritical question, I do not advise you to implement that but to find a better pattern to do what you want.

You want to sort a List of Bucket. To call Collections.sort() method, Bucket needs to implements Comparable (and so to define compareTo method).

You should define an interface implemented by your "filling" elements

interface Element {
    float getVolume();
    void setVolume(float volume);
}
class Oil implements Element {
    float volume;

    @Override
    public float getVolume() {
        return volume;
    }

    @Override
    public void setVolume(float volume) {
        this.volume = volume;
    }
}
class Water implements Element {
    float volume;

    @Override
    public float getVolume() {
        return volume;
    }

    @Override
    public void setVolume(float volume) {
        this.volume = volume;
    }
}

Now you can define Bucket class:

class Bucket implements Comparable<Bucket> {
    Element filling;

    @Override
    public int compareTo(Bucket o) {
        return Float.compare(filling.getVolume(), o.filling.getVolume());
    }
}

And this code:

public static void main(String[] args) {
    List<Bucket> elems = new LinkedList<>();
    Bucket o = new Bucket();
    o.filling = new Oil();
    o.filling.setVolume(5);

    Bucket w = new Bucket();
    w.filling = new Water();
    w.filling.setVolume(12);

    elems.add(w);
    elems.add(o);
    Collections.sort(elems);
    for(Bucket b: elems) {
        System.out.println(b.filling.getVolume());
    }
}

Will print:

5.0
12.0

Shame on me I wrote the whole code, but it's easier to understand by reading this one than reading a bad explanation I could write.

Upvotes: 1

Related Questions