[2017/2/24] Project Java: CH 9. java.lang패키지와 유용한 클래스 코드

1.
public class Hello{
public static void main(String[] args){
Value v1 = new Value(10);
Value v2 = new Value(10);

if (v1.equals(v2)){
System.out.println(“v1과 v2가 같습니다”);
}else{
System.out.println(“다르다”);
}
}
}

class Value{
int value;

Value(int value){
this.value = value;
}
}

-Object 클래스에 있는 equals()는 참조변수의 값으로 판단한다.

2.
class Person{
long id;

public boolean equals(Object obj){
if(obj != null && obj instanceof Person){
return id == ((Person)obj).id;
}else{
return false;
}
}

Person(long id){
this.id = id;
}
}

public class Hello{
public static void main(String[] args){
Person p1 = new Person(8011081111222L);
Person p2 = new Person(8011081111222L);

if(p1.equals(p2))
System.out.println(“같다”);
else
System.out.println(“다르다”);
}
}

-이런 식으로 클래스에서 equals 오버라이딩 해줘야 한다.

3.
public class Hello{
public static void main(String[] args){
String str1 = “abc”;
String str2 = “abc”;

System.out.println(str1.hashCode());
System.out.println(str2.hashCode());
}
}

-String클래스에서는 hasCode()가 오버라이딩되어 있다.

4.
class Card{
String kind;
int number;

Card(){
this(“SPADE”, 1);
}

Card(String kind, int number){
this.kind = kind;
this.number = number;
}
}

public class Hello{
public static void main(String[] args){
Card c1 = new Card();
System.out.println(c1.toString());
System.out.println(c1);
}
}

-클래스 이름 @ 해시코드의 형식으로 출력된다.
-toString() 붙이지 않아도 같은 형식으로 출력된다.

5.
public class Hello{
public static void main(String[] args){
java.util.Date today = new java.util.Date();

System.out.println(today);
}
}

-Date 클래스와 String 클래스는 toString()이 오버라이딩 되어있다.

6. clone() 메서드
class Point implements Cloneable{
int x;
int y;

Point(int x, int y){
this.x = x;
this.y = y;
}

public String toString(){
return “x=”+x+”, y=”+y;
}

public Point clone(){
Object obj = null;
try{
obj = super.clone();
}catch(CloneNotSupportedException e){

}
return (Point)obj;
}
}

public class Hello{
public static void main(String[] args){
Point original = new Point(3,5);
Point copy = original.clone();
System.out.println(original);
System.out.println(copy);
}
}

-공변 반환타입을 이용하여 clone() 오버라이딩할 때 반환형은 Point로 한다.

7. 얕은 복사와 깊은 복사
class Point{
int x;
int y;

Point(int x, int y){
this.x = x;
this.y = y;
}

public String toString(){
return “(“+x+”, “+y+”)”;
}
}

class Circle implements Cloneable{
Point p;
double r;

Circle(Point p, double r){
this.p = p;
this.r = r;
}

public Circle shallowCopy(){
Object obj = null;
try{
obj = super.clone();
}
catch(CloneNotSupportedException e){}
return (Circle)obj;
}

public Circle deepCopy(){
Object obj = null;
try{
obj = super.clone();
}
catch(CloneNotSupportedException e){}

Circle c = (Circle) obj;
c.p = new Point(this.p.x, this.p.y);
return c;
}

public String toString(){
return “p: “+p+”, r= “+r;
}
}

public class Hello{
public static void main(String[] args){
Circle c1 = new Circle(new Point(1,1), 2.0);
Circle c2 = c1.shallowCopy();
Circle c3 = c1.deepCopy();

c1.p.x = 3;
c1.p.y = 4;
System.out.println(c1);
System.out.println(c2);
System.out.println(c3);
}
}

-Object 클래스의 경우 선언과 동시에 초기화하지 않으면 초기화되지 않았다며 에러가 뜬다.

8.
public class Hello{
public static void main(String[] args){
String str1 = “abc”;
String str2 = “abc”;

System.out.println(“String str1 = \”abc\”;”);
System.out.println(“String str2 = \”abc\”;”);

System.out.println(“str1 == str2 “+(str1==str2));
System.out.println(“str1.equals(str2) “+(str1.equals(str2)));

String str3 = new String(“abc”);
String str4 = new String(“abc”);

boolean b1 = (str3 == str4);
boolean b2 = (str4.equals(str3));

System.out.println(b1+”, “+b2);

}
}

9. split과 StringJoiner
import java.util.StringJoiner;

public class Hello{
public static void main(String[] args){
String animals = “cat,dog,horse”;
String[] arr = animals.split(“,”);

System.out.println(String.join(“-“, arr));

StringJoiner sj = new StringJoiner(“/”, “[“, “]”);
for(String s : arr){
sj.add(s);
}

System.out.println(sj.toString());

}
}
-join에서 구분자가 먼저 쓰인다.
-StringJoiner는 new 이용해서 새로운 인스턴스 생성 후 add로 각각 추가한다.

10. 문자 인코딩 변환
import java.io.UnsupportedEncodingException;
import java.util.StringJoiner;

public class Hello{
static String joinByteArr (byte[] bArr) throws Exception{
StringJoiner sj = new StringJoiner(“:”, “[“, “]”);

for(byte b : bArr){
sj.add(String.format(“%02X”, b) );

}
return sj.toString();
}

public static void main(String[] args) throws Exception{
String str = “가”;

byte[] bArr = str.getBytes(“UTF-8”);
byte[] bArr2 = str.getBytes(“CP949”);

System.out.println(joinByteArr(bArr));
System.out.println(joinByteArr(bArr2));

System.out.println(new String(bArr, “UTF-8”));
System.out.println(new String(bArr2, “CP949”));
}

}

-getBytes 등 문자 인코딩 할 때는 encoding Exception 던져줘야 한다.

11. 기본형 값과 String 간의 변환
public class Hello{
public static void main(String[] args){
int iVal = 100;
String strVal = String.valueOf(iVal);

double dVal = 200.0;
String strVal2 = dVal + “”;

double sum = Integer.parseInt(“+”+strVal) + Double.parseDouble(strVal2);
double sum2 = Integer.valueOf(strVal) + Double.valueOf(strVal2);

System.out.println(String.join(“”,strVal,”+”,strVal2,”=”)+sum);
System.out.println(strVal+”+”+strVal2+”=”+sum2);
}
}

12.
public class Hello{
public static void main(String[] args){
String fullName = “Hello.java”;

int index = fullName.indexOf(‘.’);

String fileName = fullName.substring(0, index);
String ext = fullName.substring(index+1);

System.out.println(fileName);
System.out.println(ext);
}
}

13.
public class Hello{
public static void main(String[] args){
StringBuffer str1 = new StringBuffer(“abc”);
StringBuffer str2 = new StringBuffer(“abc”);

boolean b1 = (str1 == str2);
boolean b2 = (str1.equals(str2));

System.out.println(b1);
System.out.println(b2);

String str3 = str1.toString();
System.out.println(str3);
}
}

-StringBuffer는 equals는 오버라이딩되지 않았으나 toString()은 오버라이딩 되어있다.

14.
public class Hello{
public static void main(String[] args){
StringBuffer sb = new StringBuffer(“01”);
StringBuffer sb2 = sb.append(23);
sb.append(‘4’).append(56);

StringBuffer sb3 = sb.append(78);
sb3.append(9.0);

System.out.println(sb);
System.out.println(sb2);
System.out.println(sb3);

System.out.println(sb.deleteCharAt(10));
System.out.println(sb.delete(3, 6));
System.out.println(sb.insert(3, “abc”));
System.out.println(sb.replace(6,sb.length(),”END”));

System.out.println(sb.capacity());
System.out.println(sb.length());
}
}

-append()의 경우 반환형이 StringBuffer의 주소이다.

15. Math 클래스
import static java.lang.Math.*;
import static java.lang.System.*;

public class Hello{
public static void main(String[] args){
double val = 90.7552;
out.println(round(val));

val += 100;
out.println(round(val));

out.println(round(val)/100);
out.println(round(val)/100);
out.println();
out.println(ceil(1.1));
out.println(floor(1.5));
out.println(round(1.1));
out.println(“round: “+round(1.5));
out.println(“rint: “+rint(1.5));
out.println(round(-1.5));
out.println(rint(-1.5));
out.println(ceil(-1.5));
out.println(floor(-1.5));
}
}

-rint와 round의 차이점:
1. round의 반환형은 int, rint는 double
2. 음수에서 round는 -0.5를 0으로, rint는 -1.000000로 표시

16.
import static java.lang.Math.*;
import static java.lang.System.*;

public class Hello{
public static void main(String[] args){
int i = Integer.MIN_VALUE;

out.println(i);
out.println(-i);

try{
out.println(negateExact(10));
out.println(negateExact(-10));

out.println(negateExact(i));
}
catch(ArithmeticException e){
out.println(“예외 발생했다 마”);
out.println(negateExact((long)i));
}
}
}

-Exact 붙는 애들은 오버플로우 발생했을 때 발생했음을 알려준다. 따라서 try-catch 문을 통해 구성해줘야 한다.
-그렇다고 오버플로우를 자동 처리해주는 것은 아니니 발생 시 더 큰 기본형으로 바꿔줘야 한다.

17.
import static java.lang.Math.*;
import static java.lang.System.*;

public class Hello{
public static void main(String[] args){
int x1 = 1, y1 = 1;
int x2 = 2, y2 = 2;

double c = sqrt(pow(x2-x1, 2) + pow(y2 – y1, 2));
out.printf(“c = %f%n”, c);
}
}

18. 래퍼 클래스
public class Hello{
public static void main(String[] args){
Integer i = new Integer(20);
Integer i2 = new Integer(20);

System.out.println(i==i2);
System.out.println(i.equals(i2));

System.out.println(i.compareTo(i2));
System.out.println(i.toString());

System.out.println(Integer.MAX_VALUE);
}
}

-래퍼 클래스는 equals, toString이 오버라이딩되어 있다.
-다만 비교연산자를 쓸 수 없기 때문에 compareTo 메서드를 사용한다.

19.
public class Hello{
public static void main(String[] args){
int i = new Integer(“100”).intValue();
int i2 = Integer.parseInt(“100”);
Integer i3 = Integer.valueOf(“100”);

int i4 = Integer.parseInt(“100”, 2);
int i5 = Integer.parseInt(“100”, 16);
int i6 = Integer.parseInt(“FF”, 16);

Integer i7 = Integer.valueOf(“100”, 2);
Integer i8 = Integer.valueOf(“100”, 16);
Integer i9 = Integer.valueOf(“FF”, 16);

System.out.println(i);
System.out.println(i2);
System.out.println(i3);
System.out.println(i4);
System.out.println(i5);
System.out.println(i6);
System.out.println(i7);
System.out.println(i8);
System.out.println(i9);
}
}

20. java.util.Objects 클래스
import java.util.*;
import static java.util.Objects.*;

public class Hello{
public static void main(String[] args){
String[][] str2D = new String[][]{{“aaa”, “bbb”},{“AAA”, “BBB”}};
String[][] str2D2 = new String[][]{{“aaa”, “bbb”},{“AAA”, “BBB”}};

for(String[] tmp : str2D){
System.out.println(Arrays.toString(tmp)); //[aaa, bbb]의 형식으로 출력하기 위한 Arrays.toString은 java.util.Arrays에 있다.
}

for(String[] tmp: str2D){
for(String str: tmp){
System.out.println(str);
}
}

System.out.println(Objects.equals(str2D, str2D2));
System.out.println(Objects.deepEquals(str2D, str2D2));

Comparator c = String.CASE_INSENSITIVE_ORDER;

System.out.println(compare(“aa”, “bb”, c));
}
}

-compare는 Comparator 이용(얘는 util 패키지 내의 누군가 사용하는 듯)
-deepEquals는 Objects 상위 클래스에서 사용되고 있는 듯. Objects.deepEquals(~) 형식으로 써줘야 함.

21.
import java.util.*;

public class Hello{
public static void main(String[] args){
Random rand = new Random(1);
Random rand2 = new Random(1);

for(int i = 0; i < 5; i ++){
System.out.println(i + “: “+ rand.nextInt());
}

for(int i = 0; i < 5; i++){
System.out.println(i + “: “+rand2.nextInt());
}
}
}

-시드 값이 같은 Random 인스턴스들은 같은 값을 가진다.

22.
import java.util.*;

public class Hello{
public static void main(String[] args) throws Exception{
Random rand = new Random();
int[] number = new int[100];
int[] counter = new int[10];

for(int i = 0; i < number.length; i++){
System.out.print(number[i] = rand.nextInt(10));
}

System.out.println();

for(int i = 0; i < number.length; i ++){
counter[number[i]]++;
}

for(int i = 0; i < counter.length; i++){
System.out.println(printGraph(‘#’, counter[i]));
}
}

public static String printGraph(char ch, int value){
char[] bar = new char[value];

for(int i = 0; i < bar.length; i++){
bar[i] = ch;
}
return new String(bar);
}
}

23.
import java.util.*;

public class Hello{
public static void main(String[] args){
for(int i = 0; i < 10; i++){
System.out.print(getRand(5, 10)+ “, “);
}
System.out.println();

int[] result = fillRand(new int[10], new int[]{2,3,7,5});

System.out.println(Arrays.toString(result));
}

public static int[] fillRand (int[] arr, int from, int to){
for(int i = 0; i < arr.length; i++){
arr[i] = getRand(from, to);
}

return arr;
}

public static int[] fillRand(int[] arr, int[] data){
for (int i = 0; i < arr.length; i++){
arr[i] = data[getRand(0, data.length – 1)];
}

return arr;
}

public static int getRand(int from, int to){
return (int)(Math.random() * (Math.abs(to-from) +1) + Math.min(from, to));
}
}

 

댓글 남기기