문서의 이전 판입니다!
equals() 메서드
public boolean equals(Object obj){
return (this == obj);
}
package chapter12;
public class EqualsEx {
public static void main(String[] args) {
Obj obj1 = new Obj(100);
Obj obj2 = new Obj(100);
if (obj1.equals(obj2)) {
System.out.println("obj1 객체와 obj2 객체는 같음");
} else {
System.out.println("obj1 객체와 obj2 객체는 다름");
}
Obj obj3 = obj1;
if (obj1.equals(obj3)) {
System.out.println("obj1 객체와 obj3 객체는 같음");
} else {
System.out.println("obj1 객체와 obj3 객체는 다름");
}
ObjOverride objo1 = new ObjOverride(100);
ObjOverride objo2 = new ObjOverride(100);
if (objo1.equals(objo2)) {
System.out.println("objo1 객체와 objo2 객체는 같음");
} else {
System.out.println("objo1 객체와 objo2 객체는 다름");
}
}
}
class Obj {
int obj_var;
Obj(int obj_var) {
this.obj_var = obj_var;
}
}
class ObjOverride {
int obj_var;
ObjOverride(int obj_var) {
this.obj_var = obj_var;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof ObjOverride) {
return true;
} else {
return false;
}
}
}
package chapter12;
public class EqualsEx2 {
public static void main(String[] args) {
String str1 = new String("abc");
String str2 = new String("abc");
if(str1 == str2) {
System.out.println("str1 객체와 str2 객체는 같음");
} else {
System.out.println("str1 객체와 str2 객체는 다름");
}
if(str1.equals(str2)) {
System.out.println("str1 문자열과 str2 문자열은 같음");
} else {
System.out.println("str1문자열과 str2 문자열은 다름");
}
}
}
package chapter12;
public class HahsCodeEx {
public static void main(String[] args) {
String str1 = new String( "abc");
String str2 = new String( "abc");
System.out.println("str1.hashCode():"+str1.hashCode()) ;
System.out.println("str2.hashCode():"+str2.hashCode()) ;
System.out.println("System.identityHashCode(str1):"+
System.identityHashCode(str1)) ;
System.out.println("System.identityHashCode(str2):"+
System.identityHashCode(str2)) ;
}
}
package chapter12;
public class HashCodeEx2 {
public static void main(String[] args) {
Hash v1 = new Hash(20);
Hash v2 = new Hash(20);
System.out.println(v1.hashCode());
System.out.println(v2.hashCode());
System.out.println ("v1 객체 진짜 해쉬값 :"+System.identityHashCode(v1));
System.out.println ("v2 객체 진짜 해쉬값 :"+System.identityHashCode(v2));
}
}
class Hash {
int value;
Hash(int value) {
this.value = value;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Hash) {
Hash v = (Hash)obj;
return value == v.value;
} else {
return false;
}
}
@Override
public int hashCode() {
return value;
}
}
public String toString(){
return getClass().getName()+ "@" + integer.toHexString(hashCode));
}
package chapter12;
public class ToStringEx {
public static void main(String[] args) {
Fruit f = new Fruit("사과", "빨강");
System.out.println(f);
}
}
class Fruit {
String name;
String color;
public Fruit(String name, String color) {
this.name = name;
this.color = color;
}
}
package chapter12;
public class ToStringEx2 {
public static void main(String[] args) {
Fruit2 f = new Fruit2("사과", "빨강");
System.out.println(f);
}
}
class Fruit2 {
String name;
String color;
public Fruit2(String name, String color) {
this.name = name;
this.color = color;
}
@Override
public String toString() {
return "과일 이름 : "+this.name+"\n과일 색상 : "+this.color;
}
}
package chapter12;
import java.util.Date;
public class ToStringDateEx {
public static void main(String[] args) {
Date now = new Date();
System.out.println(now);
}
}
clone() 메서드
package chapter12;
public class ClonEx {
public static void main(String[] args) {
String[] arr = {"홍길동", "이순신", "김유신", "안중근"};
String[] arr2 = arr.clone();
System.out.println(arr == arr2);
for (String v : arr2) {
System.out.println(v);
}
String[] arr3 = new String[arr.length];
System.arraycopy(arr, 0, arr3, 0, arr.length);
System.out.println(arr == arr3);
for (String v : arr3) {
System.out.println(v);
}
}
}
package chapter12;
public class PropertyEx {
public static void main(String[] args) {
for (String var : System.getenv().keySet()) {
System.out.println(var + "=" + System.getenv(var));
}
}
}
package chapter12;
public class ClassEx {
public static void main(String[] args) {
EnvEx env = new EnvEx();
// 객체를 이용해서 생성
Class c1 = env.getClass();
System.out.println(c1.getName());
// 문자열 주소로 생성
try {
Class c2 = Class.forName("chapter12.PropertyEx");
System.out.println(c2.getName());
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
}
}
package chapter12.string;
public class StringEx {
public static void main(String[] args) {
int score = 90;
System.out.println("당신의 점수는 " + score + "입니다."); // 자동형변환
//String s = score; // 데이터타입이 달라 에러
String s = String.valueOf(score); // String으로 형변환
String s2 = score + ""; // 문자열을 + 연산하여 String으로 형변환
}
}
package chapter12.string;
public class StringEx3 {
public static void main(String[] args) {
String sum = "";
for (int i=1; i<=5; i++) {
sum += i;
}
System.out.println(sum);
}
}
package chapter12.string;
public class StringEx2 {
public static void main(String[] args) {
String name1 = "홍길동";
String name2 = "홍길동";
if (name1 == name2) {
System.out.println("name1 == name2");
} else {
System.out.println("name1 != name2");
}
if (name1.equals(name2)) {
System.out.println("name1.equals(name2)");
} else {
System.out.println("!name1.equals(name2");
}
String name3 = new String("홍길동");
String name4 = new String("홍길동");
if (name3 == name4) {
System.out.println("name3 == name4");
} else {
System.out.println("name3 != name4");
}
if (name3.equals(name4)) {
System.out.println("name3.equals(name4)");
} else {
System.out.println("!name3.equals(name4");
}
}
}
package chapter12.string;
public class StringEx4 {
public static void main(String[] args) {
String text = "Hello My Name is Hong Gil Dong";
System.out.println("0번 인덱스 : "+text.charAt(0));
for (int i=0; i<text.length(); i++) {
System.out.println(text.charAt(i));
}
}
}
package chapter12.string;
public class StringEx5 {
static String s1;
static String s2 = "";
public static void main(String[] args) {
System.out.println(s1);
System.out.println(s2);
}
}
package chapter12.string;
public class StringEx6 {
public static void main(String[] args) {
String s1 = "";
System.out.println("s1.length():"+s1.length());
System.out.println("".equals(s1));
}
}
package chapter12.string;
public class StringEx7 {
public static void main(String[] args) {
String str = "Hello My Name is Hong Gil Dong";
System.out.println(str.charAt(6)); // 6번 인덱스의 문자
System.out.println(str.equals("Hello My Name is Hong Gil Dong")); // 문자열값 비교
System.out.println(str.indexOf("Hong")); // "Hong" 문자열의 위치
System.out.println(str.indexOf('H')); // 'H'문자의 위치
System.out.println(str.substring(17)); // 17번 인덱스부터 끝까지 잘라냄
System.out.println(str.substring(6, 13)); // 6번 인덱스부터 13전(12번 인덱스)까지 문자열
System.out.println(str.toLowerCase()); // 소문자로 변경
System.out.println(str.toUpperCase()); // 대문자로 변경
System.out.println(str.length()); // 문자열의 길이
System.out.println(str.startsWith("Hello")); // "Hello"으로 시작하는지 여부
System.out.println(str.endsWith("Dong")); // "Dong"으로 끝나는지 여부
System.out.println(str.replace("Hong", "Kim")); // "Hong"을 "Kim"으로 치환
System.out.println(str.replaceAll("Name", "NickName")); // "Name"을 "NickName"으로 치환
System.out.println(str.toString());
str = " 안녕 하세요, 반갑습니다. ";
System.out.println(str.trim()); // 앞뒤 공백 제거
// 모든 공백을 제거하는 방법
System.out.println(str.replace(" ", ""));
str = String.valueOf(10); // 기본자료형 int를 문자열로 변환
str = String.valueOf(10.5); // 기본자료형 double을 문자열로 변환
str = "홍길동,이순신,유관순,안중근";
String[] arr = str.split(","); // ,를 구분자로 나눠서 배열로 리턴
for (int i=0; i<arr.length; i++) {
System.out.println(i+"번 인덱스 값 = "+arr[i]);
}
}
}
package chapter12.string;
public class StringEx8 {
public static void main(String[] args) {
String[] str = {"1", "2", "3", "4"};
int sum1 = 0;
for (int i=0; i<str.length; i++) {
sum1 += Integer.parseInt(str[i]);
}
System.out.println("sum1 = "+sum1);
long sum2 = 0;
for (int i=0; i<str.length; i++) {
sum2 += Long.parseLong(str[i]);
}
System.out.println("sum2 = "+sum2);
double sum3 = 0;
for (int i=0; i<str.length; i++) {
sum3 += Double.parseDouble(str[i]);
}
System.out.println("sum3 = "+sum3);
}
}
package chapter12.stringbuffer;
public class StringEx9 {
public static void main(String[] args) {
String str1 = "abcd";
String str2 = "abcd";
System.out.println("str1 = "+System.identityHashCode(str1));
System.out.println("str2 = "+System.identityHashCode(str2));
// 기본 객체에 + 연산 후 다시 대입
str1 = str1 + "efg";
System.out.println("str1 = "+System.identityHashCode(str1));
}
}
package chapter12.stringbuffer;
public class StringBufferEx {
public static void main(String[] args) {
StringBuffer sb1 = new StringBuffer("abcd");
System.out.println("문자열 연결전 sb1 = "+System.identityHashCode(sb1));
sb1.append("efgh");
System.out.println("문자열 연결후 sb1 = "+System.identityHashCode(sb1));
System.out.println(sb1.toString().equals("abcdefgh"));
}
}
package chapter12.stringbuffer;
public class StringBufferEx2 {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
// 메서드 체이닝으로 여러 타입의 매개변수값을 StringBuffer 객체의 문자열값에 추가
sb.append("abc").append(123).append('A').append(false);
System.out.println(sb);
// 2~3번 인덱스값 삭제
sb.delete(2, 4);
System.out.println(sb);
// 4번 인덱스값 삭제
sb.deleteCharAt(4);
System.out.println(sb);
// 5번 인덱스에 == 추가
sb.insert(5,"==");
System.out.println(sb);
// 6번 인덱스에 1.23 추가(문자열로 변환)
sb.insert(6,1.23);
System. out.println(sb);
}
}
package chapter12.stringbuffer;
public class StringBufferEx3 {
public static void main(String[] args) {
// 시작
long start = System.currentTimeMillis();
String str = "";
for (int i=0; i<1000000; i++) {
str += i;
}
// 끝
long end = System.currentTimeMillis();
System.out.println( "실행 시간 : " + ( end - start )/1000);
}
}
package chapter12.stringbuffer;
public class StringBufferEx4 {
public static void main(String[] args) {
// 시작
long start = System.currentTimeMillis();
StringBuffer sb = new StringBuffer();
for (int i=0; i<1000000; i++) {
sb.append(i);
}
// 끝
long end = System.currentTimeMillis();
System.out.println( "실행 시간 : " + ( end - start )/1000);
}
}
package chapter12;
public class MathEx {
public static void main(String[] args) {
System.out.println("Math.abs(10)=" + Math.abs(10));
System.out.println("Math.abs(-10)=" + Math.abs(-10));
System.out.println("Math.abs(3.1415)=" + Math.abs(3.1415));
System.out.println("Math.abs(-3.1415)=" + Math.abs( 3.1415));
System.out.println("Math.ceil(5.4)=" + Math.ceil(5.4));
System.out.println("Math.ceil(-5.4)=" + Math.ceil(-5.4));
System.out.println("Math.floor(5.4)=" + Math.floor(5.4));
System.out.println("Math.floor(-5.4)=" + Math.floor(-5.4));
System.out.println("Math.max(5,4)=" + Math.max(5,4));
System.out.println("Math.max(5.4,5.3)=" + Math.max(5.4,5.3));
System.out.println("Math.min(5,4)=" + Math.min(5,4));
System.out.println("Math.min(5.4,5.3)=" + Math.min(5.4,5.3));
System.out.println("Math.random()=" + Math. random());
System.out.println("Math.rint(5.4)=" + Math.rint(5.4));
System.out.println("Math.rint(-5.4)=" + Math.rint(-5.4));
System.out.println("Math.round(5.4)=" + Math.round(5.4));
System.out.println("Math.round(5.5)=" + Math.round(5.5));
}
}
package chapter12;
public class RoundEx {
public static void main(String[] args) {
// 원주율을 소수점 3자리로 반올림
double v1 = Math.PI * 1000;
double v2 = Math.round(v1);
double v3 = v2 / 1000.0;
System.out.println(v3);
// 한줄로 출력
System.out.println(Math.round(Math.PI * 1000)/1000.0);
}
}
package chapter12;
public class WrapperEx {
public static void main(String[] args) {
// 정수 10이 Integer 클래스 객체로 변환 (boxing)
Integer i1 = new Integer(10);
Integer i2 = new Integer(10);
System.out.println("i1==i2 : " + (i1==i2));
System.out.println("i1.equals(i2) : " + (i1.equals(i2)));
System.out.println("i1.toString() : " + i1.toString());
//i1 객체가 100 정수로 변환 (unboxing)
System.out.println("i1==10 : " + (i1==10));
int i3 = 10;
System.out.println("i1==i3 : " + (i1==i3));
}
}
package chapter12;
public class WrapperEx2 {
public static void main(String[] args) {
System.out.println("정수의 최대값 :" + Integer.MAX_VALUE);
System.out.println("정수의 최소값 :" + Integer.MIN_VALUE);
System.out.println("byte의 최대값 :" + Byte.MAX_VALUE);
System.out.println("byte의 최소값 :" + Byte.MIN_VALUE);
System.out.println("정수의 사이즈 :" + Integer.SIZE);
System.out.println("float의 사이즈 :" + Float.SIZE);
System.out.println("double의 사이즈 :" + Double.SIZE);
}
}
별도로 명시하지 않을 경우, 이 위키의 내용은 다음 라이선스에 따라 사용할 수 있습니다: CC Attribution-Share Alike 4.0 International