compare, comparable

탱귤생귤·2023년 5월 7일

JAVA

목록 보기
11/20

In this code, compare method wasn't that close to my mind. The tricky part was how the method is telling the computer this is descending list or ascending list.

package collections;

public class Student implements Comparable<Student>{

	private int id;
	private String name;
	
	public Student(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public String toString() {
		return id+" "+name;
	}

	@Override
	public int compareTo(Student that) {
		return Integer.compare(that.id, this.id);
	}

	
}
package collections;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class AscendingStudentComparator implements Comparator<Student>{

	@Override
	public int compare(Student student1, Student student2) {
		
		return Integer.compare(student1.getId(), student2.getId());
	}
	
}

public class StudentsCollectionRunner {

	public static void main(String[] args) {
		List<Student> students=List.of(new Student(1,"Ranga"), new Student(100,"Adam"), new Student(2,"Eve"));
		List<Student> studentsAl=new ArrayList<>(students);
		
		
		
		System.out.println(students);
		
		Collections.sort(studentsAl);//can't sort in this way if studentAl is not implementing comparable
		System.out.println("Desc"+studentsAl);
		
//		Collections.sort(studentsAl, new AscendingStudentComparator());
		
		studentsAl.sort(new AscendingStudentComparator());
		System.out.println("AscendingStudentComparator " + studentsAl);
		
	}
}

My answer

When we see this code, it means descending.

	public int compareTo(Student that) {
		return Integer.compare(that.id, this.id);
	}

Because, the first Student goes to this.id and it will be 1, also the second Student goes tothat.id and it will be 100. But in the code, that.idis the first element, so when the method is executed, that.id-this.id will be 99. And, this tells the computer it is Descendant.

0개의 댓글