Comparable & Comparator Interface

PersonStudentInterface

/////////////////////////////////

import java.util.*;

class Person implements Comparable<Person>
{
private static int count = 0; // static (class) variables

protected String name; // instance variables
protected int age; // instance variables

public Person()
{
//System.out.println(“Person Constructor”); // this(“”, 0); error: call to this must be first statemenht in constructor
this(“”, 0);
}

public Person(String name, int age)
{
count++;
this.name = name;
this.age = age;
}

public Person(Person other)
{
this(other.name, other.age);
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public int getAge()
{
return age;
}

public void setAge(int age)
{
this.age = age;
}

@Override
public boolean equals(Object other) // Object.equals overriding
{
if (other instanceof Person) {
Person that = (Person) other;
return that.canEqual(this) && this.getName().equals(that.getName()) && this.getAge() == that.getAge();
}
return false;
}

@Override
public int hashCode() {
return (41 * getName().hashCode() + getAge());
}

public boolean canEqual(Object other) {
return (other instanceof Person);
}

@Override
public String toString() // Object.toString() overriding
{
return “Person Name: ” + name + ” Age: ” + age;
}

public void print() // instance methods
{
System.out.println(“Person Name: ” + name + ” Age: ” + age);
}

public void set(String name, int age)
{
this.name = name;
this.age = age;
}

public void set(Person other)
{
this.name = other.name;
this.age = other.age;
}

public Person clone()
{
Person p = new Person(this.name, this.age);
return p;
}

public static void printCount() // static (class) methods
{
System.out.println(“Person Count: ” + count);
}

public static int getCount() { return count; } // static (class) methods
public static void setCount(int value) { count = value; } // static (class) methods

public int compareTo(Person other)
{
String thisName = this.getName().toUpperCase();
String otherName = ((Person)other).getName().toUpperCase();

//ascending order
return thisName.compareTo(otherName);
//descending order
//return otherName.compareTo(thisName);
}

public static Comparator<Person> AgeComparator
= new Comparator<Person>() {

public int compare(Person p1, Person p2) {

int age1 = p1.getAge();
int age2 = p2.getAge();

//ascending order
return age1 – age2;

//descending order
//return age2 – age1;
}

};

}

///////////////////////////////////////////////////////////////////////////////////////

class Student extends Person
{
private static int count = 0; // static (class) variables
protected int id;

public Student()
{
id = 5208;
}

public Student(String name, int age, int id)
{
super(name, age);
this.id = id;
count++;
}

public int getID()
{
return id;
}

public void setID(int id)
{
this.id = id;
}

@Override
public boolean equals(Object other) // Object.equals overriding
{
if (other instanceof Student) {
Student that = (Student) other;
return that.canEqual(this) && this.getName().equals(that.getName()) && this.getAge() == that.getAge() && this.getID() == that.getID();
}
return false;
}

@Override
public int hashCode() {
return (41 * super.hashCode() + getID());
}

public boolean canEqual(Object other) {
return (other instanceof Student);
}

@Override
public String toString() // Object.toString() overriding
{
return “Student Name: ” + name + ” Age: ” + age + ” ID: ” + id;
}

public void superPrint()
{
super.print();
}

public void print() // Person class print() method overriding
{
System.out.println(“Student Name: ” + name + ” Age: ” + age + ” ID: ” + id);
}

public void set(String name, int age, int id)
{
super.set(name, age);
this.id = id;
}

public void set(String name, int age)
{
super.set(name, age);
}

public void set(Student other)
{
this.set(other.name, other.age, other.id);
}

public void set(Person other)
{
if (other instanceof Person)
super.set(other);
else
this.set((Student)other);
}

public Student clone()
{
Student s = new Student(this.name, this.age, this.id);
return s;
}

public static void printCount() // static (class) methods
{
System.out.println(“Student Count: ” + count);
}

public static int getCount() { return count; } // static (class) methods
public static void setCount(int value) { count = value; } // static (class) methods

public int compareTo(Student other)
{
String thisName = this.getName().toUpperCase();
String otherName = ((Student)other).getName().toUpperCase();

//ascending order
return thisName.compareTo(otherName);
//descending order
//return otherName.compareTo(thisName);
}

public static Comparator<Student> AgeComparator
= new Comparator<Student>() {
public int compare(Student p1, Student p2) {
int age1 = p1.getAge();
int age2 = p2.getAge();

//ascending order
return age1 – age2;

//descending order
//return age2 – age1;
}

};

public static Comparator<Student> IDComparator
= new Comparator<Student>() {
public int compare(Student p1, Student p2) {
int id1 = p1.getID();
int id2 = p2.getID();

//ascending order
return id1 – id2;

//descending order
//return id2 – id1;
}

};
}

 

class PersonStudentTest
{

public static void print(Object[] array) {
for(Object o : array) {
System.out.println(o);
}
}

public static void main(String[] args)
{

///////////////////////////////////////////////////////////////////////

Student[] sList = new Student[3];
sList[0] = new Student(“Kevin”, 0, 222);
sList[1] = new Student(“Jason”, 1, 333);
sList[2] = new Student(“John”, 2, 111);

System.out.println(“STUDENT SORT BY NAME (DEFAULT)!!!”);
Arrays.sort(sList);
print(sList);

System.out.println(“STUDENT SORT by AGE!!!”);
Arrays.sort(sList, Student.AgeComparator);
print(sList);

System.out.println(“STUDENT SORT by ID!!!”);
Arrays.sort(sList, Student.IDComparator);
print(sList);

///////////////////////////////////////////////////////////////////////
Student[] sList2 = new Student[3];
sList2[0] = new Student(“Kevin”, 0, 222);
sList2[1] = new Student(“Jason”, 1, 333);
sList2[2] = new Student(“John”, 2, 111);

System.out.println(“STUDENT SORT BY NAME (anonymous method)!!!”);
Arrays.sort(sList2, new Comparator<Student>() {
public int compare(Student s1, Student s2) {
return s1.getName().toUpperCase().compareTo(s2.getName().toUpperCase());
}
});
print(sList2);

System.out.println(“STUDENT SORT by AGE (anonymous method)!!!”);
Arrays.sort(sList2, new Comparator<Student>() {
public int compare(Student s1, Student s2) {
return s1.getAge() – s2.getAge();
}
});
print(sList2);

System.out.println(“STUDENT SORT by ID (anonymous method)!!!”);
Arrays.sort(sList2, new Comparator<Student>() {
public int compare(Student s1, Student s2) {
return s1.getID() – s2.getID();
}
});
print(sList2);

///////////////////////////////////////////////////////////////////////
Student[] sList3 = sList2;

System.out.println(“STUDENT SORT BY NAME (lambda)!!!”);
Arrays.sort(sList3, (Student ss1, Student ss2) ->
ss1.getName().compareTo(ss2.getName())
);
Arrays.stream(sList3).forEach((s) -> System.out.println(s));

System.out.println(“STUDENT SORT by AGE (lambda)!!!”);
Arrays.sort(sList3, (Student ss1, Student ss2) ->
Integer.compare(ss1.getAge(), ss2.getAge())
);
Arrays.stream(sList3).forEach((s) -> System.out.println(s));

System.out.println(“STUDENT SORT by ID (lambda)!!!”);
Arrays.sort(sList3, (Student ss1, Student ss2) ->
Integer.compare(ss1.getID(), ss2.getID())
);
Arrays.stream(sList3).forEach((s) -> System.out.println(s));

///////////////////////////////////////////////////////////////////////
List<Student> sList4 = new ArrayList<Student>();
sList4.add(new Student(“Kevin”, 0, 222));
sList4.add(new Student(“Jason”, 1, 333));
sList4.add(new Student(“John”, 2, 111));

System.out.println(“STUDENTLIST SORT BY NAME (lambda)!!!”);
sList4.sort((Student ss1, Student ss2) ->
ss1.getName().compareTo(ss2.getName())
);
sList4.forEach((s) -> System.out.println(s));

System.out.println(“STUDENTLIST SORT by AGE (lambda)!!!”);
sList4.sort((Student ss1, Student ss2) ->
ss1.getAge() – ss2.getAge()
);
sList4.forEach((s) -> System.out.println(s));

System.out.println(“STUDENTLIST SORT by ID (lambda)!!!”);
sList4.sort((Student ss1, Student ss2) ->
ss1.getID() – ss2.getID()
);
sList4.forEach((s) -> System.out.println(s));

}

}

Person Array

Person[] pArray = new Person[5];

// 만약 Person 객체를 하나만 생성한 후 for문에서 공유해 사용할 경우
// 마지막으로 입력된 데이터로 모든 데이터값이 치환됨
Person p = new Person();
for (int i = 0; i < 5; i++) {
System.out.print(“\n\nEnter Person name : “);
Scanner input = new Scanner(System.in);
p.setName(input.nextLine()); // 입력정보
System.out.print(“\n\nEnter Person age [int] : “);
p.setAge(input.nextInt()); // 입력정보
p.Print();
pArray[i] = p; // 리스트에 들어간 모든 원소는 동일한 p
}

System.out.println(“pArray : ” + Arrays.toString(pArray));

Person[] pArray = new Person[5];
// 아래와 같이 for문 안에 Person p = new Person()와같이
// 새로운 객체를 생성해야 각자 다르게 입력된 정보가 들어가게 됨
for (int i = 0; i < 5; i++) {

Person p = new Person();

System.out.print(“\n\nEnter Person name : “);
Scanner input = new Scanner(System.in);
p.setName(input.nextLine()); // 입력정보
System.out.print(“\n\nEnter Person age [int] : “);
p.setAge(input.nextInt()); // 입력정보
p.Print();

pArray[i] = p; // 이때 p는 새로운 Person객체

}

System.out.println(“pArray2 : ” + Arrays.toString(pArray2));

 

Array vs ArrayList

int[] integerArray = new int[3];

integerArray[0] = 1;

integerArray[1] = 2;

integerArray[2] = 3;

for (int i : integerArray) System.out.println(i);

for (int j=0; j<integerArray.length; j++) System.out.println(integerArray[ j ]);

int k = 0;

while (k < integerArray.length) System.out.println(integerArray[k++]);

 

ArrayList<Integer> integerList = new ArrayList<Integer>();

integerList.add(1); //cannot store primitive in ArrayList, instead autoboxing will convert int to Integer object

integerList.add(2); //cannot store primitive in ArrayList, instead autoboxing will convert int to Integer object

integerList.add(3); //cannot store primitive in ArrayList, instead autoboxing will convert int to Integer object

for (int m : integerList) System.out.println(m);

for (int n=0; n<integerList.size(); n++) System.out.println(integerList.get(n));

Iterator<Integer> itr = integerList.iterator();

while (itr.hasNext()) System.out.println(itr.next());

Lab3

Lab3-ImageManager

java2-lab3-ImageManager

Lab3_1~ Lab3_5 프로젝트 디렉토리 안에 모든 파일(src/*.java & bin/*.class)와 보고서 (3~5장)를 넣고 Lab3_학번_이름.zip 압축한 후 e-learning(http://lms.dankook.ac.kr/index.jsp)으로 제출 & 보고서는 출력해서 수업시간에 제출

Lab3_1 – Photo class (static vs non-static, private vs public, getter vs setter), array of Photo

Lab3_2 – array of Photo from File Input

Lab3_3 – ImageConverter/ImageResizer

Lab3_4 – array of Photo

Lab3_5 – ArrayList of Photo

Lab2

Lab2-DirectoryImageConverter

java2-lab2-DirectoryImageConverter

Lab2_1~ Lab2_5 프로젝트 디렉토리 안에 모든 파일(src/*.java & bin/*.class)와 보고서 (2~3장)를 넣고 Lab2_학번_이름.zip 압축한 후 e-learning(http://lms.dankook.ac.kr/index.jsp)으로 제출

Lab2_1 – array(String[] commands), foreach, parameter passing

Lab2_2 – String, class

Lab2_3 – String substring 메소드, file/directory

Lab2_4 – BufferedReader 클래스 (“commands.ini”)

Lab2_5 – recursive call

Lab1 Review

Lab1_Review

import java.util.Scanner;

class Arithmetic {
public static int add(int n, int m) {
return n + m;
}

public static int divide(int n, int m) throws ArithmeticException {
return n / m;
}
}

public class Lab1 {

// 5.1 Scanner, user input
static int input1, input2;
static Scanner scan = new Scanner(System.in);
public static void getUserInput()
{
System.out.print(“Please enter [input1]: “);
input1 = scan.nextInt();
System.out.print(“Please enter [input2]: “);
input2 = scan.nextInt();
scan.nextLine();
}
// 5.2 get ‘q’-key
public static boolean getUserExitKey() {
System.out.print(“Press q-key to exit the program or enter-key to enter new user input: “);
String s = scan.nextLine();
if (s.contentEquals(“q”))
return true;
else
return false;
}

// 2. method 정의
static int add(int i, int j) {
int k = i + j;
return k;
}

public static void main(String[] args) {
// TODO Auto-generated method stub

// println
System.out.println(“test”);

// 0. String +
String a = “1”;
String b = “2”;
String c = a + b;
System.out.println(“a=” + a);
System.out.println(“b=” + b);
System.out.println(“c=” + c);

// 1. command line arguments
if (args.length == 3) {
System.out.println(args[0]);
System.out.println(args[1]);
System.out.println(args[2]);
}

// 2.1 method를 사용하지 않는다면 아래 코드 부분이 반복적으로 사용되어야 함
int i = 1; // local variable
int j = 2; // local variable
int k = i + j; // local variable
System.out.println(“i=” + i);
System.out.println(“j=” + j);
System.out.println(“k=” + k);

i = 10;
j = 20;
k = i + j;
System.out.println(“i=” + i);
System.out.println(“j=” + j);
System.out.println(“k=” + k);

i = 100;
j = 200;
k = i + j;
System.out.println(“i=” + i);
System.out.println(“j=” + j);
System.out.println(“k=” + k);

// 2.2 method 사용
int k2 = add(1, 2);
System.out.println(“k2=” + k2);
k2 = add(10, 20);
System.out.println(“k2=” + k2);
k2 = add(i, j);
System.out.println(“k2=” + k2);

// 3. class 사용
int k3 = Arithmetic.add(1, 2);
System.out.println(“k3=” + k3);
k3 = Arithmetic.add(10, 20);
System.out.println(“k3=” + k3);
k3 = Arithmetic.add(i, j);
System.out.println(“k3=” + k3);

// 4. for-loop 사용
for (int n=0; n<10; n++) {
int k4 = Arithmetic.add(n, n*2);
System.out.println(“k4[” + n + “]=” + k4);
}

// 5.1 Scanner 클래스 사용 사용자 입력
System.out.println(“두 수를 입력하여 덧셈을 합니다”);
getUserInput();
int k5 = Arithmetic.add(input1, input2);
System.out.println(“k5=” + k5);

// 5.2 do-while-loop 사용
System.out.println(“\n\n”);
do {
getUserInput();
int k6 = Arithmetic.add(input1, input2);
System.out.println(“k6=” + k6);
} while (!getUserExitKey());

// 5.3 try/catch/throws
try {
System.out.println(“두 수를 입력하여 나눗셈을 합니다”);
getUserInput();
int k7 = Arithmetic.divide(input1, input2);
System.out.println(“k7=” + k7);
} catch (ArithmeticException e) {
e.printStackTrace();
}

System.out.println(“done”);
}
}