0
//For Class A
    public class NameCompare implements Comparator<A>
    {
        public int compare(A a1, A a2){

            if(a1.findName()> a2.findName()){
                return 1;
            } 
             else if(a1.findName()== a1.findName())
                    return 0;
            else {
                return -1;
            }
        }
    }
//For Class B
     public class ACompare implements Comparator<B>
        {
            public int compare(B b1, B b2){

                if(b1.getId()> b2.getId()){
                    return 1;
                } 
                 else if((b1.getId()== (b2.getId()())
                        return 0;
                else {
                    return -1;
                }
            }
    }
//Main Class
       ArrayList<A> copy = (ArrayList<A>)B.getA();
       Collections.sort(copy, new NameCompare());
       Collections.sort(copy, new ACompare());     
       for (A a : copy) {
          System.out.println(a);
          }

I am new to Java. As far as I know, the method above may be an incorrect way to sort a list by using the attributes from 2 different classes. Assuming class B holds an array list of class A. How would I sort the list, lets say I would want to display an ascending id, then the name

Synetrix
  • 59
  • 2
  • 12
  • may i know what is relationship with A, B and Pet class? – Vishal Gajera Feb 29 '16 at 15:08
  • sorry it was a typo, it was supposed to be just A and B B class holds an array list of A.class. But then I want to sort the list according to attributes from A and B – Synetrix Feb 29 '16 at 15:13
  • Please upload your own code this does not specify everything that what we need to understand.. Almost unable to understand what u exactly trying to do – Vikrant Kashyap Feb 29 '16 at 15:16
  • You will need to show the Class hierarchy for A and B at a minimum. You Sorting an ArrayList of A using NameCompare, which is fine and sorts on the name. But, then you turn around and sort using ACompare, which is a Comparator for B..but you are sorting type A's, so this won't work.. Unless A extends B or something like that. So, there is not enough information. – pczeus Feb 29 '16 at 15:17

1 Answers1

0

Your question is not completely clear, but I would suggest that (using your example of name and id) you define a class Person with two fields: name and id. Then you can define a comparator that compares the id first and then the name. In this way, you can sort objects of type Person in the right way.

If you need to have "lists of lists", that should be sorted, then you need to explain your issue more thoroughly.

J Fabian Meier
  • 33,516
  • 10
  • 64
  • 142