정렬(Collections sort Comparable Comparator)
package my.examples.javaexam.goodsExample;
public class Student implements Comparable<Student>{
private String name;
@Override
public int compareTo(Student o) {
return name.compareTo(o.name);
}
private int kor;
private int eng;
private int math;
public Student(){
}
public Student(String name, int kor, int eng, int math) {
this.name = name;
this.kor = kor;
this.eng = eng;
this.math = math;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getKor() {
return kor;
}
public void setKor(int kor) {
this.kor = kor;
}
public int getEng() {
return eng;
}
public void setEng(int eng) {
this.eng = eng;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", kor=" + kor +
", eng=" + eng +
", math=" + math +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
if (kor != student.kor) return false;
if (eng != student.eng) return false;
if (math != student.math) return false;
return name != null ? name.equals(student.name) : student.name == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + kor;
result = 31 * result + eng;
result = 31 * result + math;
return result;
}
}
package my.examples.javaexam.goodsExample;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Score {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
Student std1 = new Student("cheongwon", 100, 90, 80);
Student std2 = new Student("misoo", 80, 100, 90);
Student std3 = new Student("kyeongsu",90,80,100);
students.add(std1);
students.add(std2);
students.add(std3);
System.out.println(students);
Collections.sort(students);
System.out.println(students);
Collections.sort(students,new CompartorKor());
System.out.println(students);
Collections.sort(students,new CompartorEng());
System.out.println(students);
Collections.sort(students,new CompartorMath());
System.out.println(students);
}
}
class CompartorKor implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
return o1.getKor() - o2.getKor();
}
}
class CompartorEng implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
return o1.getEng() - o2.getEng();
}
}
class CompartorMath implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
return o1.getMath() - o2.getMath();
}
}
'Java' 카테고리의 다른 글
Day 9. maven에서 json사용하기 (0) | 2018.12.17 |
---|---|
어노테이션 (0) | 2018.12.15 |
Day 7. 과제(JAVA IO) (0) | 2018.12.12 |
Day 7. 과제 (0) | 2018.12.12 |
Day 6. Java 로또 프로그램(객체지향) (0) | 2018.12.12 |