-2

Is there any way sorting an arraylist of objects in java without using Comparator or comparable ,I have Student class as shown below i need to Sort the Students Objects based on their Age., Is it possible to Sort ? without using implementing Comparator or Comparable in class

//Class of Students
//comparable or comparator Not implemented

 public class Student  {
        private String studentname;
        private int rollno;
        private int studentage;

        public Student(int rollno, String studentname, int studentage) {
             this.rollno = rollno;
             this.studentname = studentname;
             this.studentage = studentage;
        }

        public String getStudentname() {
             return studentname;
        }
        public void setStudentname(String studentname) {
        this.studentname = studentname;
        }
        public int getRollno() {
        return rollno;
        }
        public void setRollno(int rollno) {
        this.rollno = rollno;
        }
        public int getStudentage() {
        return studentage;
        }
        public void setStudentage(int studentage) {
        this.studentage = studentage;
        }   
    }


    import java.util.*;
    public class ArrayListSorting  {

         public static void main(String args[]){

         //Array of Student Objects
           ArrayList<Student> arraylist = new ArrayList<Student>();
           arraylist.add(new Student(223, "Chaitanya", 26));
           arraylist.add(new Student(245, "Rahul", 24));
           arraylist.add(new Student(209, "Ajeet", 32));

           Collections.sort(arraylist);

           for(Student str: arraylist){
                System.out.println(str.getStudentage());
           }
         }
    }
  • Can you use lambda functions? this is using the comparator but without writing much code. `Collections.sort(list, (s1, s2) -> s1.getStudentage().compareTo(s2. getStudentage));` Any specific reason you don't want to use the comparator ? – zstring Aug 18 '16 at 06:59
  • No, its not possible, except programming the algo by yourself – Henning Luther Aug 18 '16 at 06:59
  • Are you sure that the statement `System.out.println(str);` works? I didn't know the `println()` function to be taking arguments of type `java.lang.Object`. – progyammer Aug 18 '16 at 07:21
  • 1
    @HenningLuther How can you say it is impossible and name a possibility in the same sentence? – Fildor Aug 18 '16 at 07:31
  • @zstring Tried on elitmus Test Editor but it doesn't worked out – Raghu Gunasekaran Aug 18 '16 at 09:34

6 Answers6

2

Assuming you're coming from the most strict interpretation of this then the answer is still, and always, yes.

Sorting algorithms sort data without concern of the language they're implemented in. So, if you can't use any sneaky work around then the point of your exercise is to implement a sorting algorithm. Seems reasonable.

I'm not going to give you a sort algorithm. But, depending on how you want to go about it, you could provide a utility class (like Java does), accept an ArrayList, and sort it with your choice of sorting algo. You would obviously do this based on the age of the student.

Lists.sort(yourArrayList); : would be as good as anything else.

ChiefTwoPencils
  • 13,548
  • 8
  • 49
  • 75
1

Yes, it is possible to sort an ArrayList by using the get() and set() methods instead of Comparable and Comparator:

public class ArrayListSortWithoutComparator {

    public static void main(String[] args) {
        ArrayList < Integer > arraylist = new ArrayList < Integer > ();

        arraylist.add(10);
        arraylist.add(5);
        arraylist.add(4);
        arraylist.add(2);

        for (int i = 0; i < arraylist.size(); i++) {
            for (int j = arraylist.size() - 1; j > i; j--) {
                if (arraylist.get(i) > arraylist.get(j)) {
                    int tmp = arraylist.get(i);
                    arraylist.set(i,arraylist.get(j));
                    arraylist.set(j,tmp);
                }
            }
        }
        for (int i : arraylist) {
            System.out.println(i);
        }
    }
}

Output:

2
4
5
10
marcelovca90
  • 2,673
  • 3
  • 27
  • 34
0

No, if the ArrayList is of custom object type then in such case you have two options for sorting - Comparable and Comparator interfaces.

However you can use Collections.sort() method to sort a simple array list.

DimaSan
  • 12,264
  • 11
  • 65
  • 75
0

The answer to your question is Yes. Here's how: You can simply use a Selection Sort technique to iterate over the ArrayList like you do for an array.

for(int i=0;i<arraylist.size()-1;i++){
    int m = i;
    for(int j=i+1;j<arraylist.size();j++){
        if(araylist.get(m).studentage > arraylist.get(j).studentage)
            m = j;
    }
    //swapping elements at position i and m
    Student temp = arraylist.get(i);
    arraylist.set(i, arraylist.get(m));
    arraylist.set(m, temp);
}

This would sort the Student objects in ascending order of ages.

progyammer
  • 1,498
  • 3
  • 17
  • 29
  • " i need to Sort the Students Objects **based on their Age**" :) But I guess you can leave the change up for OP's practice. – Fildor Aug 18 '16 at 07:37
  • Oops. Wait a second. They can just change "rollno" to "studentage" in the above program. I still made the edit. – progyammer Aug 18 '16 at 07:38
0

You said, "s it possible to Sort ? without using implementing Comparator or Comparable in class"

The answer to your question, then, is Yes. You can implement a custom Comparator and pass that to this sort overload. You still implement Comparator, but not as a member of the class of the items you're sorting.

See Using comparator to make custom sort for an example.

Community
  • 1
  • 1
Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
-2

Yes its called

yourArray.sort();

You should copy your Array into a new one (if you want sort only the newArray while the Data of the old one isnt sort) using :

System.arraycopy(yourArray, startIndex, newArray, );

or you can use

int[]newArray = Arrays.copyOf(yourArray, arrayLength);

In my Opinion first solution is more powerfull since you are able to merge Arrays.

MOC
  • 9
  • 2