1

It is possible to sort a collection of objects with comparable interface and when you find some attribute equal increment value?

I need to keep a collection ordered by a numeric attribute, identify attributes and increase equal value without losing the ordering

3
  • 2
    Have you tried something? Commented Nov 1, 2013 at 19:21
  • Then you need to write a comparator. Commented Nov 1, 2013 at 19:23
  • Parts of this question are unclear. Are you asking if modifying items in a collection can break the collection ordering? Certainly, if the modifications are taking place on fields that the comparator is using to create the order. Commented Nov 1, 2013 at 20:15

1 Answer 1

1

Based on the limited description in the question, you can try with the following code:

class Student implements Comparable < Student >
{
  int rollno;
  String name;
  int age;
  Student (int rollno, String name, int age)
  {
    this.rollno = rollno;
    this.name = name;
    this.age = age;
  }

  public int compareTo (Student st)
  {
    if (age == st.age)
      {
        st.age += 1;
        return -1;
      }

    else if (age > st.age)
      return 1;
    else
      return -1;
  }
}

When you run this code with the following, you get the desired output :

Executing Code:

public static void main (String[]args)
  {
    ArrayList < Student > al = new ArrayList < Student > ();
    al.add (new Student (101, "Vijay", 23));
    al.add (new Student (106, "Ajay", 23));
    al.add (new Student (105, "Jai", 21));

    Collections.sort (al);
    for (Student st:al)
      {
        System.out.println (st.rollno + " " + st.name + " " + st.age);
      }
  }

Output:

105 Jai 21
106 Ajay 23
101 Vijay 24
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.