Search Results for 'Java !!!'

54 POSTS

  1. 2015.04.10 Collection_ Set 오름차순 내림차순
  2. 2015.04.07 String_2
  3. 2015.04.07 String_1
  4. 2015.04.07 HashCode
  5. 2015.04.07 equals_2
  6. 2015.04.07 equals
  7. 2015.04.06 Exception을 만들어서도 쓴다.
  8. 2015.04.06 예외처리 Exception( 런타임과 컴파일 차이 )
  9. 2015.04.06 예외처리 Exception
  10. 2015.04.05 C++과 Java의 다른점

Collection_ Set 오름차순 내림차순

Posted 2015. 4. 10. 11:22

기본 디폴트. Object가 오름 차순으로 되어 있다.

내림차순은 직접 해줘야한다.

 

package chap11;
import java.util.*;

public class ComparatorEx1 {
 public static void main(String[] args) {
  TreeSet set1 = new TreeSet();      // 기본 오름차순.
  TreeSet set2 = new TreeSet( new Descending2() ); // 내림 차순으로 바꾼다.
  int[] score = {30, 50, 10, 20, 40};
  for( int i=0 ; i<score.length ; i++ ){
   set1.add( score[i] );
   set2.add( score[i] );
  }
  System.out.println("set1 : " + set1);
  System.out.println("set2 : " + set2);
 }
}

class Descending2 implements Comparator {
 @Override
 public int compare( Object o1, Object o2 ){
  Comparable c1 = (Comparable)o1;
  Comparable c2 = (Comparable)o2;
  return c1.compareTo(c2) * (-1);
 }
}

 

'Java !!!' 카테고리의 다른 글

Collection_ HastSet  (0) 2015.04.10
Collection_ TreeSet  (0) 2015.04.10
String_2  (0) 2015.04.07
String_1  (0) 2015.04.07
HashCode  (0) 2015.04.07

String_2

Posted 2015. 4. 7. 14:35

package chap9;

import java.io.ObjectInputStream.GetField;

// String 클래스의 메서드 연습

public class StringEx2 {
 public static void main(String[] args) {
  String s = new String("ABCDEFGH");
  
  // charAt(4) : 4번 인덱스의 문자를 리턴
  System.out.println(s.charAt(4)); // E
  
  // compareTo() : 나의 문자 - 대상문자의 차를 리턴
  // 정렬에서 사용되는 메서드
  System.out.println(s.compareTo("abc")); // -32
  
  // IgnoreCase : 대소문자 구별없이 무시하고 문자열이 같은지?
  System.out.println(s.compareToIgnoreCase("abcdefgh")); // 0
  
  // concat : s + "abc" 두 문자열을 연결해주는 메서드
  System.out.println(s.concat("abc")); // ABCDEFGHabc
  
  // endsWith("FGH") : s 문자열의 끝이 FGH? 맞으면 true, 아니면 false
  System.out.println(s.endsWith("FGH")); // true
  
  // equals("ABCDEFGH") : "ABCDEFGH" 문자열의 내용이 같은지?
  System.out.println(s.equals("ABCDEFGH")); // true
  System.out.println(s.equalsIgnoreCase("abcdefgh")); // true
  

  String s1 = new String("This is a String");
  // 2 : i 문자의 위치(index)를 리턴, 중복일 경우 가장 앞의 index를 리턴
  System.out.println(s1.indexOf('i'));  
  System.out.println(s1.indexOf("is"));  // 2
  
  // 13 : 뒤에 넘긴 값의 index번째 부터 검색해서 index를 넘김
  System.out.println(s1.indexOf('i',7));  
  System.out.println(s1.indexOf("i",5));  // 5 : 5번 인덱스도 포함된다.

  // 5 : 찾는건 뒤에서 부터찾는데 리턴 index값은 앞에서부터 샌다.
  System.out.println(s1.lastIndexOf("is")); 
  
  // 16 : 문자열의 길이.
  System.out.println(s1.length());  
  
  // 모든 i를 Q로 바꾼다.
  System.out.println(s1.replace('i', 'Q'));
  System.out.println(s1.replace("is", "IS")); // 모든 is를 IS로 바꾼다.
  System.out.println(s1.replaceAll("is", "IS")); // 문자열 is를 IS로 바꾼다.
  
  // 시작이 해당 문자와 같으면 true, 다르면 false
  System.out.println(s1.startsWith("This"));
  
  // 5번 인덱스 부터 끝까지를 부분 문자열로 리턴
  System.out.println(s1.substring(5));
  System.out.println(s1.substring(5, 13)); // 5번부터 13-1번 까지 출력(12번 index)
  
  // 모두 소문자로 출력, 모두 대문자로 출력
  System.out.println(s1.toLowerCase());
  System.out.println(s1.toUpperCase());
  
  String s2 = "a,b,c,d,e,f,g,h";
  // split(",") : ,를 기준으로 문자열을 분리. 해당 문자열을 기준으로 문자열을 분리!!
  String[] tokens = s2.split(",");
  for( String str : tokens ){
   System.out.println(str);
  }
  
  // trim() : 양쪽의 공백을 제거. 단, 문자열 사이의 공백은 제거하지 않는다.
  System.out.println(new String("   a b c   ").trim());
  
  // valueOf : 기본형을 문자열로 변형 하는 메서드
  System.out.println(String.valueOf(true) + "123");
  System.out.println(true + "123");
  
  // 문자열 => 기본형 메서드
  System.out.println(Integer.parseInt("123") + 5);
  System.out.println(Float.parseFloat("12.3") + 10);
  
  // JDK 5.0이후 버전에서만 가능
  // %.숫자만큼 짜르고, 반올림 한다.
  // format("형식제어문자",값)
  String sf = String.format("%.2f", 12.3456);
  System.out.println(sf);
  
 }
}


 

'Java !!!' 카테고리의 다른 글

Collection_ TreeSet  (0) 2015.04.10
Collection_ Set 오름차순 내림차순  (0) 2015.04.10
String_1  (0) 2015.04.07
HashCode  (0) 2015.04.07
equals_2  (0) 2015.04.07

String_1

Posted 2015. 4. 7. 14:35

package chap9;

// String 클래스 예제
// 클래스중에 유일하게 할당 연산자로 객체생성이 가능한 클래스
// 클래스중엘 유일하게 + 연산자를 사용 할 수 있는 클래스
// String = String + 기본자료형

public class StringEx1 {
 public static void main(String[] args) {
  // string은 유일하게 할당연상자로 생성이 가능하다.
  // 이렇게 생성 할 경우 힙 영역이 아닌 클래스영역(상수풀)에 생성이 되고
  // 같은 값의 str2는 클래스영역(상수풀)의 str1값을 참조하게 되어,
  // 객체 비교시 같은 값이 나온다.
  String str1 = "abc"; 
  String str2 = "abc";
  if( str1 == str2 ) System.out.println("str1 == str2");
  else System.out.println("str1 != str2");
  
  if( str1.equals(str2) ) System.out.println("str1.equals(str2):true");
  else System.out.println("str1.equals(str2):false");
  System.out.println();
  
  String str3 = new String("abc");
  String str4 = new String("abc");
  if( str3 == str4 ) System.out.println("str3 == str4");
  else System.out.println("str3 != str4 ");
  
  if( str3.equals(str4) ) System.out.println("str3.equals(str4):true");
  else System.out.println("str3.equals(str4):false");
  System.out.println();
  
  String s5 = String.valueOf(100);
  System.out.println(s5);
  s5 = "" + 100;
  System.out.println(s5);
 }
}

'Java !!!' 카테고리의 다른 글

Collection_ Set 오름차순 내림차순  (0) 2015.04.10
String_2  (0) 2015.04.07
HashCode  (0) 2015.04.07
equals_2  (0) 2015.04.07
equals  (0) 2015.04.07

HashCode

Posted 2015. 4. 7. 14:35

package chap9;

// 해쉬코드란 객체를 구별하는 고유의 값( 주소값 )
// 두 객체의 해쉬코드값이 다른 경우는 두 객체는 서로 다른 객체다.
// hashCode() 메서드는 내용이 같으면 같은값이 나오도록
// 오버라이딩이 가능 하다.
// -> Collection에서 다시 설명

// 객체의 내용이 같은지를 판단하는 기준이 되는 메서드는
// equals() 메서드와 hashCode() 메서드를 사용 한다.

public class HashCodeEx1 {
 public static void main(String[] args) {
  String str1 = new String("abc");
  String str2 = new String("abc");
  
  // 스트링은 오버라이딩이 되어있다. 같은 hashCode값이 나온다.
  System.out.println(str1.hashCode());
  System.out.println(str2.hashCode());
  
  if( str1 == str2 ) System.out.println("두 문자열은 같다");
  else System.out.println("두 문자열은 다르다");
  
  // 원래의 해쉬코드값을 구하기 위해서는( 오버라이딩 하지않은 원래의 해쉬값 )
  System.out.println(System.identityHashCode(str1));
  System.out.println(System.identityHashCode(str2));
  System.out.println();
  
  
  Value2 v1 = new Value2(10);
  Value2 v2 = new Value2(10);
  System.out.println(v1.hashCode());
  System.out.println(v2.hashCode());
  System.out.println(System.identityHashCode(v1));
  System.out.println(System.identityHashCode(v2));
 }
}

 

'Java !!!' 카테고리의 다른 글

String_2  (0) 2015.04.07
String_1  (0) 2015.04.07
equals_2  (0) 2015.04.07
equals  (0) 2015.04.07
Exception을 만들어서도 쓴다.  (0) 2015.04.06

equals_2

Posted 2015. 4. 7. 14:34

package chap9;

class Value2{
 int value;
 Value2(int value){
  this.value = value;
 }
 
 // 객체의 내용을 비교해서 같으면 true
 // 다르면 false 리턴하는 메서드로 오버라이딩
 @Override
 public boolean equals( Object obj ){
  if( obj instanceof Value2 ){
   Value2 v = (Value2)obj;
   if( value == v.value ) return true;
   else return false;
  }
  else return false;
 }
}

public class Equalsx2 {
 public static void main(String[] args) {
  Value2 v1 = new Value2(10);
  Value2 v2 = new Value2(10);
  
  if( v1 == v2 ) System.out.println("v1객체와 v2객체는 같습니다.");
  else System.out.println("v1객체와 v2객체는 다릅니다.");
  
  if( v1.equals(v2) ) System.out.println("v1.equals(v2) : true");
  else System.out.println("v1.equals(v2) : false");
  
  System.out.println(v1.hashCode());
  System.out.println(System.identityHashCode(v1));
 }
}

'Java !!!' 카테고리의 다른 글

String_1  (0) 2015.04.07
HashCode  (0) 2015.04.07
equals  (0) 2015.04.07
Exception을 만들어서도 쓴다.  (0) 2015.04.06
예외처리 Exception( 런타임과 컴파일 차이 )  (0) 2015.04.06

equals

Posted 2015. 4. 7. 14:34

package chap9;

// Equels 메서드 연습

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

// Object 클래스의 equals 메서드는 객체비교방식 구현
// 객체비교는 == 연산자로도 가능
// equals 메서드는 내용비교하는 방식으로 오버라이딩 필요
// 대부분의 클래스는 equals 메서드를 내용비교 방식으로
// 오버라이딩해서 사용하고 있다. ( string )

public class Equalsx1 {
  
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Value v1 = new Value(10);
  Value v2 = new Value(10);
  
  if( v1 == v2 ) System.out.println("v1객체와 v2객체는 같습니다.");
  else System.out.println("v1객체와 v2객체는 다릅니다.");
  
  if( v1.equals(v2) ) System.out.println("v1.equals(v2) : true");
  else System.out.println("v1.equals(v2) : false");
  
  
  v2 = v1;
  if( v1 == v2 ) System.out.println("v1객체와 v2객체는 같습니다.");
  else System.out.println("v1객체와 v2객체는 다릅니다.");
  
  if( v1.equals(v2) ) System.out.println("v1.equals(v2) : true");
  else System.out.println("v1.equals(v2) : false");
 }
}

'Java !!!' 카테고리의 다른 글

HashCode  (0) 2015.04.07
equals_2  (0) 2015.04.07
Exception을 만들어서도 쓴다.  (0) 2015.04.06
예외처리 Exception( 런타임과 컴파일 차이 )  (0) 2015.04.06
예외처리 Exception  (0) 2015.04.06

Exception을 만들어서도 쓴다.

Posted 2015. 4. 6. 13:44

package chap8;

// Exception 클래스를 상속 받아 MyException을 만들기

class MemoryException extends Exception{
 public MemoryException(){
  super("메모리가 부족합니다.");
 }
}

class SpaceException extends Exception{
 final int ERR_CODE;
 public SpaceException(){
  super("설치 공간이 부족합니다.");
  ERR_CODE = 100;
 }
 
 public int getErrCode(){
  return ERR_CODE;
 }
}

public class ExceptionEx8{
 boolean isSpace() { return false; }
 boolean isMemory() { return true; }
 public static void main( String[] args ){
  ExceptionEx8 m = new ExceptionEx8();
  try{
   if( !m.isMemory() )
    throw new MemoryException();
   if( !m.isSpace() )
    throw new SpaceException();
  } catch( MemoryException e ){
   System.out.println("메모리가 부족합니다.");
  } catch( SpaceException e ){
   System.out.println("저장 공간이 부족합니다.");
   System.out.println("ERR_CODE : " + e.ERR_CODE);
   e.printStackTrace();
  }
 }
}

 

'Java !!!' 카테고리의 다른 글

equals_2  (0) 2015.04.07
equals  (0) 2015.04.07
예외처리 Exception( 런타임과 컴파일 차이 )  (0) 2015.04.06
예외처리 Exception  (0) 2015.04.06
C++과 Java의 다른점  (0) 2015.04.05

package chap8;

public class ExceptionEx5 {
 public static void main(String[] args) {
  // RuntimeException는 컴파일 중 에러는 무시하고 런타임중 에러를 잡겠다는 것.
  // 걍 Exception은 컴파일 도중도 포함 된다.
  throw new RuntimeException("예외 고의로 발생2");
 }
}

 

'Java !!!' 카테고리의 다른 글

equals  (0) 2015.04.07
Exception을 만들어서도 쓴다.  (0) 2015.04.06
예외처리 Exception  (0) 2015.04.06
C++과 Java의 다른점  (0) 2015.04.05
동적할당 정적할당 개념  (0) 2015.04.04

예외처리 Exception

Posted 2015. 4. 6. 13:09

package chap8;

// throws : 예외처리
// tyr mehod1() -> method1()에서 method2 호출 -> method2에서 catch 실행
// -> catch에 throw가 있으면 호출한 곳으로 알림 -> method1에서 catch 호출
// -> method1을 호출한 곳의 catch 호출. 로 흘러간다.

public class ExceptionEx7 {
 public static void main(String[] args){
  try{
   method1();
  } catch( Exception e ){ // throw로 넘어 왔다면 catch 실행한다.
   System.out.println("main에서 예외처리");
  }
 }
 
 private static void method1() throws Exception {
  try{
   method2();
  } catch ( Exception e){
   System.out.println("method1에서 예외처리");
   throw e; // 2. 2에서 넘어온 에러 내용을 method1을 호출한 곳으로 간다.
  }
 }
 
 private static void method2() throws Exception {
  try{
   throw new Exception("thorws로 예외처리해야함");
  }catch ( Exception e ){
   System.out.println("method2에서 예외처리");
   throw e; // 1. 예외 재 발생 -> 호출한 곳으로 간다.
  }
 }
}

C++과 Java의 다른점

Posted 2015. 4. 5. 14:00

Static 개념

자바의 Static은 객체가 생성됨(정적으로)을 의미한다.

« PREV : 1 : 2 : 3 : 4 : 5 : 6 : NEXT »