반응형

*ArrayList

1. import

import java.util.ArrayList;

 

2. 객체 생성

// String 담는 ArrayList 생성
ArrayList<String> my_arr_list = new ArrayList<String>();

 

3. 추가 : add

my_arr_list.add("hello");
my_arr_list.add("java");
my_arr_list.add("world!");

 

4. 삭제 : remove

// 2번째 삭제
my_arr_list.remove(2);

 

5. 엘리먼트 가져오기 : get

// 1번째 원소 출력
System.out.println(my_arr_list.get(1));

 

6. ArrayList 탐색을 위한 Iterator

- 객체지향 프로그래밍에서 사용하는 반복기법이다.

// my_arr_list의 Iterator 객체 it 생성방법
Iterator<String> it = my_arr_list.iterator();

 

7. Iterator을 이용한 while문

- hasnext() : 더 순회할 엘레먼트가 있는지 알수 있다.

- Iterator명.next() : 다음 엘레먼트를 갖고 올 수 있다.

// Iterator 이용 my_arr_list의 모든 원소 출력
while( it.hasNext() ) {
	System.out.println( it.next() );
}

 

8. ArrayList 클래스의 private 맴버 변수로 Object를 담는 배열 생성

class ArrayList 
{
	private int size = 0;
    
    // object[] 타입 private 멤버변수 elementData 생성
    private Object[] elementData = new Object[5];
}

 

9. Object 타입을 인자로 받는 빈 public 메소드, addLast 생성

class ArrayList {
    private int size = 0;
    private Object[] elementData = new Object[50];

    // Object타입을 인자로 받는 빈 메소드, addLast 생성
    public boolean addLast( Object a ) {
        return true;
    }
}

 

10. Object 타입 원소 하나를 맨 마지막 위치에 추가.

class ArrayList {
    private int size = 0;
    private Object[] elementData = new Object[50];

    public boolean addLast(Object e)
    {
        // elementData의 마지막 위치에 인자 e 추가
        elementData[ size ] = e;

        size ++;
        return true;
    }
}

 

11. 중간 위치에 추가.

class ArrayList {
    private int size = 0;
    private Object[] elementData = new Object[50];

    public boolean addLast(Object e) {
        elementData[size++] = e;
        return true;
    }

    public boolean add(int index, Object element) {
        for (int i = size - 1; i >= index; i--) {
            elementData[i + 1] = elementData[i];
        }

        //elementData의 index에 데이터를 추가       
		elementData[index] = element;
        
		size++;

        return true;
    }
}

 

12. 첫번째 위치에 추가.

// 기존 add함수 이용하여 구현.

class ArrayList {
    private int size = 0;
    private Object[] elementData = new Object[50];

    public boolean addLast(Object e) {
        elementData[size++] = e;
        return true;
    }

    public boolean add(int index, Object element) {
        for (int i = size - 1; i >= index; i--) {
            elementData[i + 1] = elementData[i];
        }
        elementData[index] = element;
        size++;
        return true;
    }
   
   public boolean addFirst(Object element) {
   // add 메소드를 이용해서 데이터를 첫번째 위치에 저장하는 addFirst함수 구현
   return add( 0, element);
   
   }
}

 

13. n번째 위치 데이터 불러오기 get메서드

class ArrayList {
    private int size = 0;
    private Object[] elementData = new Object[50];

    // index에 위치한 데이터를 가져오는 get 함수
    public Object get(int index) {
        return elementData[index];
    }

    public boolean addLast(Object e)
    {
        elementData[size++] = e;
        return true;
    }

    public boolean add(int index, Object element)
    {
        for (int i = size - 1; i >= index; i--) {
            elementData[i + 1] = elementData[i];
        }
        elementData[index] = element;
        size++;
        return true;
    }
    public boolean addFirst(Object element)
    {
        return add(0, element);
    }
}
반응형
반응형

*예외처리

1. try ~ catch

try {

}
catch(Exception e) {
}

 

2. throws 

- 방법1
public class ExceptionExam{
    public int get50thItem(int []array) throws ArrayIndexOutOfBoundsException {    
        return  array[49];
    }
}

- 방법2 
public class ExceptionExam{
    public int get50thItem(int []array){
        if(array.length < 50){
            throw new IllegalArgumentException();
        }
    return  array[49];
    }
}

 

3. 사용자 정의 Exception

- Checked exception 
Exception 클래스를 상속받은 경우 Checked exception이 됩니다. 
이 경우, 반드시 오류를 처리해야 하며 만약 예외처리 하지 않으면 컴파일 오류를 발생시킵니다. 

- Unchecked exception
RuntimeException을 상속받는 경우 Unchecked exception이 됩니다. 
이 경우에는 예외처리를 하지 않아도 컴파일시에 오류를 발생시키지 않습니다.
반응형
반응형

*삼항 연산자

hour < 12? "오전" : "오후";
- hour가 12보다 작으면 오전, 아니면 오후 출력

 

*switch문

import java.util.Calendar;
public class SwitchExam {
    public static void main(String[] args) {
        // month에는 오늘이 몇 월인지 들어 있습니다.
        int month = Calendar.getInstance().get(Calendar.MONTH) + 1;
        String season = "";
        // switch문을 이용해서 season이 오늘은 어떤 계절인지 나타내게 만들어보세요.
        switch (month) {
            case 12:
            case 1:
            case 2:
                season = "겨울";
                break;
            case 3:
            case 4:
            case 5:
                season = "봄";
                break;
            case 6:
            case 7:
            case 8:
                season = "여름";
                break;
            case 9:
            case 10:
            case 11:
                season = "가을";
                break;
        }
        
        System.out.println("지금은 " + month + "월이고, " + season + "입니다.");
    }
}

 

*for each문

public class ForEachExam {
    public static void main(String[] args) {
        int [] array = {1, 5, 3, 6, 7};
        //for each문을 이용해서 array의 값을 한 줄씩 출력하세요
        for (int arr : array ) {
            System.out.println(arr);
        }
        
    }
}

 

*문자열 붙이기/자르기

public class StringExam {
    public static void main(String[] args) {
        String str1 = "안녕하세요. ";
        String str2 = "벌써 여기까지 오셨네요. 끝까지 화이팅!!";
        
        String concatResult;
        String substringResult;
        
        // 아래쪽에 코드를 작성하세요.
        concatResult = str1.concat(str2);
        
        substringResult = str1.substring(2);
        
        
        // 이 아래는 정답 확인을 위한 코드입니다. 수정하지 마세요.
        System.out.println(concatResult);
        System.out.println(substringResult);
    }
}
반응형

+ Recent posts