0

I have an arraylists filled with objects. Each object consists of two integers. How do i sort the arraylist based on the first integer while keeping the second integer with its original integer? And then how to I add all of the second integers of the sorted arraylist?

I tried this:

Collections.sort(info, new Comparator()
    {
        public int compare(M one, M two) 
        {
            return m1.getCost().compareToIgnoreCase(m2.getCost());
        }

    });

class M{
//Declares the attributes belonging to this class
private int money;
private int cost;

//Constructor method
{
    //this refers to object in which the method was called
    this.cost = cost;
    this.money = money;
}

//Returns the cost variable
public int getCost()
{
    return cost;
}

public void setCost(int cost)
{
    this.cost = cost;
}

//Returns the maximum amount
public int getMoney()
{
    return money;
}

public void setMoney(int Money)
{
    this.Money = Money;
}

}

I am new to java so any help would be greatly appreciated(:

user1755178
  • 255
  • 1
  • 4
  • 9
  • I'm sorry but I'm new to java and everything i look up suggests using a comparable interface but everything they are comparing are strings not ints – user1755178 Jan 02 '13 at 05:10
  • I tried implementing the comparable interfact but it says i cannot dereference the int – user1755178 Jan 02 '13 at 05:11
  • public int compare(Object one, Object two) { M m1 = (M) one; M m2 = (M) two; return m1.getCost().compareTo(m2.getCost()); } – user1755178 Jan 02 '13 at 05:14
  • sorrry thats not very reader-friendly – user1755178 Jan 02 '13 at 05:14
  • @user1755178 There is no "first and second" when sorting (the sort is not guaranteed to utilize the values in a stable fashion): only two objects which must be ordered in relationship to each-other. Also, the sort function does not allow any mapping operation to occur and it should be side-effect free. Perhaps sample data (input and output) would clear up the question. –  Jan 02 '13 at 05:17
  • I just dont understand how I would sort it then based on the first integer. Like if I had (11,4) and (2,4) in the arraylist, I would want (2,4) to show up first – user1755178 Jan 02 '13 at 05:19
  • `(11,4)` is not an integer. Show the full types used. When you create a new comparator it should be of type `M` (where `M` represents the objects in the array) and thus: `public int compare(M a, M b) { .. }`. –  Jan 02 '13 at 05:20
  • possible duplicate of [How to sort an arraylist of objects by a property?](http://stackoverflow.com/questions/2535124/how-to-sort-an-arraylist-of-objects-by-a-property) –  Jan 02 '13 at 05:29
  • possible duplicate of [Sorting a collection of objects](http://stackoverflow.com/questions/1206073/sorting-a-collection-of-objects) – mmmmmm Jan 02 '13 at 10:45

3 Answers3

2
import java.util.*;

public class M implements Comparator<M>{

int i,j;

M(int a, int b){
    i=a; j=b;
}

public int compare(M m1, M m2){

    return (m1.i-m2.i);
}

public boolean equals(Object o){
    if(this.i==((M)o).i)
        return true;
    else 
        return false;
}


public static void main(String args[]){

        M m1 = new M(2,1);
        M m2 = new M(3,2);
        M m3 = new M(1,3);

        ArrayList<M> a = new ArrayList<M>();
        a.add(m1);
        a.add(m2);
        a.add(m3);

                   Collections.sort(a,(Comparator<M>)m1);

                    //ArrayList a is sorted
            for(int j=0;j<a.size();j++){
        System.out.println(a.get(j).i);
    }
}
}

Implement the Comparator interface in your class so that the Collections.sort method will sort the objects using the int1 of class M. Then use Collections.sort method to sort the array. This should answer the first part of the question.

jaaw
  • 91
  • 5
1

When creating a Comparator it should be used as a Generic type with T (where T represents the objects in the array) and thus: public int compare(T a, T b) { .. }.

For instance:

new Comparator<M> {
    // Note the signature
    public int compare(M one, M two) 
    {
        // Now return a correct value based on the ordering
        // using one.getCost() and two.getCost()
        // Obviously "compareToIgnoreCase" is wrong for use with numbers.
        // Either work this out or see one of the existing/linked answers.
    }
}

If generics are not used then the signature is public int compare(Object one, Object two) and casting will likely be needed - note that there is no overload for (int, int); it is a declared method that is never used!

See also:

Community
  • 1
  • 1
1

how about this :

public class Main {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    M[] mm = new M[4];
    mm[0] = new M(11, 2);
    mm[1] = new M(11, 4);
    mm[2] = new M(4, 67);
    mm[3] = new M(4, 2);
    mm = compareM(mm);
    for (int a = 0; a < mm.length; a++) {
        System.out.println("index : "+a+" a : "+mm[a].a+" b : "+mm[a].b);
    }
}

public static M[] compareM(M[] data) {
    for (int a = 0; a < data.length - 1; a++) {
        for (int b = a + 1; b < data.length; b++) {
            if (data[a].a > data[b].a) {
                M temp = data[a];
                data[a] = data[b];
                data[b] = temp;
            }
        }
    }
    for (int a = 0; a < data.length; a++) {
        int indStart = a;
        int indEnd = a;
        for (int b = a + 1; b < data.length; b++) {
            if (data[b].a == data[a].a) {
                indEnd++;
            } else {
                b = data.length;
            }
        }
        a = indEnd;
        for (int c = indStart; c <= indEnd; c++) {
            for (int d = c + 1; d <= indEnd; d++) {
                if (data[c].b > data[d].b) {
                    M temp = data[c];
                    data[c] = data[d];
                    data[d] = temp;
                }
            }
        }
    }
    return data;
}

static class M {

    public int a, b;
    //u can have function to set value of a n b, or any function

    public M(int ax, int bx) {
        this.a = ax;
        this.b = bx;
    }
}

}

koponk
  • 452
  • 1
  • 3
  • 14