[JAVA] day5

99winnmin·2022년 6월 29일
0

java

목록 보기
6/10

JAVA 시작하기

배열이란?

int[] arr1 = new int[10];
int arr2[] = new int[10];

1.동일한 자료형의 순차적 자료 구조
2.인덱스 연산자[]를 이용하여 빠른 참조가 가능
3.물리적 위치와 논리적 위치가 동일
4.배열의 순서는 0부터 시작
5.자바에서는 객체 배열을 구현한 ArrayList를 많이 활용함

초기화 방식

int[] numbers = new int[] {10, 20, 30};  //개수 생략해야 함

int[] numbers = {10, 20, 30};            // new int[]  생략 가능 

int[] ids; 
ids = new int[] {10, 20, 30};            // 선언후 배열을 생성하는 경우는 new int[] 생략할 수 없음

객체 배열

기본 자료형 배열은 선언과 동시에 배열의 크기만큼의 메모리가 할당되지만,
객체 배열의 경우엔 요소가 되는 객체의 주소가 들어갈(4바이트, 8바이트) 메모리만 할당되고(null) 각 요소 객체는 생성하여 저장해야 함

얕은 복사

  • 객체 주소만 복사되어 한쪽 배열의 요소를 수정하면 같이 수정 됨->즉, 두 배열이 같은 객체를 가리킴
  • System.arrayCopy(src, srcPos, dest, destPos, length) 자바에서 제공되는 배열 복사 메서드
package dataStructure.array;

public class ObjectSwallowCopyTest {
    public static void main(String[] args) {
        Book[] library  = new Book[5];
        Book[] temp = new Book[5];

        library[0] = new Book("a","k");
        library[1] = new Book("b","kk");
        library[2] = new Book("c","kkk");
        library[3] = new Book("d","kkkk");
        library[4] = new Book("e","kkkkk");

        //System.arrayCopy(src, srcPos, dest, destPos, length) 자바에서 제공되는 배열 복사 메서드
        //객체 주소만 복사되는 얕은 복사
        System.arraycopy(library,0,temp,0,5);

        library[0].setAuthor("ryuSeungMin");
        library[0].setTitle("java programming");

        for (Book book : library){
            System.out.println(book);
            book.showBookInfo();
        }
        System.out.println("\n============================\n");
        for (Book book : temp){
            System.out.println(book);
            book.showBookInfo();
        }
    }
}

깊은 복사

  • 각각의 객체를 생성하여 그 객체의 값을 복사하여 배열이 서로 다른 객체를 가리키도록 함
package dataStructure.array;

public class ObjectDeepCopyTest {
    public static void main(String[] args) {
        Book[] library  = new Book[5];
        Book[] temp = new Book[5];

        library[0] = new Book("a","k");
        library[1] = new Book("b","kk");
        library[2] = new Book("c","kkk");
        library[3] = new Book("d","kkkk");
        library[4] = new Book("e","kkkkk");

        temp[0] = new Book();
        temp[1] = new Book();
        temp[2] = new Book();
        temp[3] = new Book();
        temp[4] = new Book();

        for(int i=0 ; i< library.length ; i++){
            temp[i].setTitle(library[i].getTitle());
            temp[i].setAuthor(library[i].getAuthor());
        }

        library[0].setAuthor("ryuSeungMin");
        library[0].setTitle("java programming");

        for (Book book : library){
            System.out.println(book);
            book.showBookInfo();
        }
        System.out.println("\n============================\n");
        for (Book book : temp){
            System.out.println(book);
            book.showBookInfo();
        }
    }
}

다차원 배열

  • 예제 코드
package dataStructure.array;

public class TwoDimensionTest {
    public static void main(String[] args) {
        int [][] arr =  {{1,2,3,4,5,6},{1,2,3}};

        for(int i=0 ; i<arr.length ; i++){
            for (int j=0 ; j<arr[i].length ; j++){
                System.out.print(arr[i][j]+" ");
            }
            System.out.println();
        }
    }
}

ArrayList

java.util 패키지에서 제공되는 ArrayList

  • 기존의 배열 선언과 사용 방식은 배열의 길이를 정하고 요소의 개수가 배열의 길이보다 커지면 배열을 재할당하고 복사해야 했음
  • 배열의 요소를 추가하거나 삭제하면 다른 요소들의 이동에 대한 구현을 해야 함
  • ArrayList는 객체 배열을 좀더 효율적으로 관리하기 위해 자바에서 제공해 주는 클래스
  • 이미 많은 메서드들이 최적의 알고리즘으로 구현되어 있어 각 메서드의 사용 방법만 익히면 유용하게 사용할 수 있음

주요 메서드

  • 예제코드
package dataStructure.arrayList;

import java.util.ArrayList;

public class Student {
    int studentID;
    String studentName;
    ArrayList<Subject> subjectList;

    public Student(int studentID, String studentName){
        this.studentID = studentID;
        this.studentName = studentName;
        subjectList = new ArrayList<>();
    }

    public void addSubject(String name, int score){
        Subject subject = new Subject();
        subject.setName(name);
        subject.setScorePoint(score);
        subjectList.add(subject);
    }

    public void showStudentInfo(){
        int total = 0;
        for(Subject s : subjectList){
            total += s.getScorePoint();
            System.out.println("who:"+studentName+"\tsubject: "+s.getName() +"\tscore: "+s.getScorePoint());
        }
        System.out.println("total score : "+total);
    }
}
profile
功在不舍

0개의 댓글