Yuda
Yuda

Reputation: 23

how sort a vector list using collecton frameworks java

I am trying to sort a Vector list using the Java Collections frameworks.

This is my code...

public class RiverList {

    public static void main(String[] args) {
        Vector<River> rivers = new Vector<River>();
        //name length and discharge

        River river3 = new River("Nil", 6852, 2660);
        River river5 = new River("Amazonas", 6448, 209000);
        River river1 = new River("Rhein", 1233, 2330);
        River river4 = new River("Donau", 2857, 6700);
        River river2 = new River("Oker", 128, 12);

        rivers.add(river1);
        rivers.add(river2);
        rivers.add(river3);
        rivers.add(river4);
        rivers.add(river5);

        System.out.println(rivers);

        // sort the river after length with help class collection

        System.out.println(rivers);

        // sort the river after discharge with help class collection

        System.out.println(rivers);
    }
}

public class River {
    private int length;
    private int discharge;
    private String name; 

    public River(String name, int length, int discharge) {
        this.name = name;
        this.length = length;
        this.discharge = discharge;
    }

    // getters and setters
    ...

    public String toString() {
        return name + ", Length = " + length + ", discharge = " + discharge + "\n";
    }
}

Here is what I have done, but I am stuck on how to proceed further...

public class RiverLengthComparator implements Comparator {
    public int compare(Object arg0, Object arg1) {
        return 0;
    }
}

public class RiverDischargeComparator implements Comparator {
    public int compare(Object o1, Object o2) {
        return 0;
    }
}

The output should be like this (for river length)...

("Nil", 6852, 2660);
("Amazonas", 6448, 209000);
("Donau", 2857, 6700);
("Rhein", 1233, 2330);
("Oker", 128, 12);

And for river discharge...

("Amazonas", 6448, 209000);
("Donau", 2857, 6700);
("Nil", 6852, 2660);
("Rhein", 1233, 2330);
("Oker", 128, 12);

Could someone please help me with this problem.

Upvotes: 2

Views: 185

Answers (2)

Baz
Baz

Reputation: 36884

maybe your compare method should return something else than 0 ;) Think about what you want to achieve and read the documentation of the Comparator interface.

maybe using Comparator<River> instead of just Comparator would be a first step.

In the end you might want to use Collections.sort(rivers, new RiverLengthComparator()); with the comparator you want to use.

Upvotes: 5

madhairsilence
madhairsilence

Reputation: 3870

Collections.sort(vector);

BTW What do you get from these print statements??

System.out.println(rivers);

//sort the river after length with help class colection

System.out.println(rivers);

//sort the river after discharge with help class colection


System.out.println(rivers);

Upvotes: 2

Related Questions