221005 정리

서이·2022년 10월 5일
0

수업정리

목록 보기
9/17

List 인터페이스

💡 List 컬렉션은 배열과 비슷하게 객체를 인덱스로 관리한다. 배열과의 차이는 저장 용량이 자동으로 증가하며 객체를 저장할 때 자동 인덱스가 부여된다는 것이다. 그리고 추가,삭제,검색을 위한 다양한 메소드들이 제공된다.

List컬렉션은 객체 자체를 저장하는 것이 아니라 다음 그림과 같이 객체의 번지를 참조한다. 그렇기 때문에 동일한 객체를 중복 저장할 수 있는데 이 경우 동일한 번지가 참조된다. null도 저장이 가능하며 이경우 해당
인덱스는 객체를 참조하지 않는다.

List컬렉션에 객체를 추가할 때에는 add() 메소드를 사용, 객체를 찾아올 때에는 get()메소드를 사용. 그리고 객체 삭제는 remove()메소드를 사용한다. 다음은 List 컬렉션에 String 객체를 추가,삽입,검색,삭제하는 방법이다.

List<String> list = ···;
list.add("홍길동");              //맨 끝에 객체 추가
list.add(1,"신용권");			  //지정된 인덱스에 객체 삽입
String str = list.get(1);       //인덱스로 객체 검색
list.remove(0);                 //인덱스로 객체 삭제
list.remove("신용권");           //객체 삭제

List 컬렉션에 저장된 모든 객체를 대상으로 하나씪 가져와 처리하고 싶다면 인덱스를 이용하는 방법과 향상된 for문을 이용하는 방법이 있다. 다음은 인덱스를 이용하는 방법이다. List 컬렉션의 size()메소드는 현재 저장되어 있는 객체 수를 리턴한다.

List<String> list = ···;
for(int i=0; i<list.size(); i++){
         String str = list.get(i);
}

다음은 향상된 for문을 이용하는 방법이다. List컬렉션에 저장된 객체 수만큼 반복하면서 객체를 하나씩 str 변수에 대입한다.

for(String str:list){
}

ArrayList

List인터페이스의 대표적인 구현 클래스이다.
ArrayList를 생성하기 위해서는 저장할 객체 타입을 E타입 파라미터 자리에 표기하고 기본 생성자를 호출하면 된다. 예를 들어 String을 저장하는 ArrayList는 다음과 같이 생성할 수 있다.

List list = new ArrayList();
List list = new ArrayList<>();

두 코드는 동일하게 String을 저장하는 ArrayList 객체를 생성한다.

ArrayList에 객체를 추가하면 0번 인덱스부터 차례대로 저장된다. ArrayList에서 특정 인덱스의 객체를 제거하면 바로 뒤 인덱슷부터 마지막 인덱스까지 모두 앞으로 1씩 당겨진다. 마찬가지로 특정 인덱스에 객체를 삽입하면 해당 인덱스부터 마지막 인덱스까지 모두 1씩 밀려난다.

이런 동작 때문에 저장된 객체 수가 많고 특정 인덱스에 객체를 추가하거나 제거하는 일이 빈번하다면 ArrayList보다는 나중에 학습 할 LinkedList를 사용하는 것이 좋다. 하지만 인덱스를 이용해서 객체를 찾거나 맨 마지막에 객체를 추가하는 경우에는 ArrayList가 더 좋은 성능을 발휘한다.




실습

// 1. 정보를 담을 Student 클래스 만들기.
public class Student {
		// 필요한 정보를 변수로 선언
    private int classNo;
    private String name;
    private String gitRepositoryAddress;

// 생성자를 통한 정보 입력
    public Student(int classNo, String name, String gitRepositoryAddress) {
        this.classNo = classNo;
        this.name = name;
        this.gitRepositoryAddress = gitRepositoryAddress;
    }
	// 결과 출력 시, 문자열 리턴을 위한 toString() 오버라이딩.
    @Override
    public String toString(){
        return classNo + " " + name + " " + gitRepositoryAddress;
    }
}

이 클래스는 학생의 반, 이름 ,깃허브 주소를 멤버변수로 한다.
객체가 출력될 때는 소속,이름,repository를 출력할 수 있게 toString() 메소드를 재정의한다.


// 2. Student 클래스를 활용한 List 만들기
public class Names {

// List 객체 생성.
		// Generic을 사용하여, List에는 Student 객체만 들어갈 수 있음.
    private List<String> students = new ArrayList<>();
    private List<Student> studentObjs = new ArrayList<>();

	// List의 .add()메소드를 활용한 정보 입력 메소드
		// Student 클래스에서 작성한 생성자로, 객체 생성과 동시에 List에 정보 입력
    public List<Student> getStudetObjs(){
        this.studentObjs.add(new Student(1,"김경록","https://github.com/Kyeongrok/like-lion-java"));
        this.studentObjs.add(new Student(1,"권하준","https://github.com/dongyeon-0822/java-project-exercise"));
        this.studentObjs.add(new Student(1,"조성윤","https://github.com/kang-subin/Java"));
        this.studentObjs.add(new Student(3,"안예은","https://github.com/KoKwanwun/LikeLion.git"));
        this.studentObjs.add(new Student(1,"남우빈","https://github.com/lcomment/Algorithm_Solution--Java/tree/main/LikeLion"));


	// 선언한 리턴타입(List<Student>)에 맞춰 스스로를 리턴
        return this.studentObjs;
    }


    public List<String> names(){
        this.students.add("조성윤");
        this.students.add("안예은");
        this.students.add("남우빈");
        this.students.add("최경민");
        this.students.add("안준휘");
        this.students.add("하채민");
  
     

        return this.students;
    }
}

학생의 속성을 넣어둘 List를 만든다.
LikeLion2thNames의 생성자이다. LikeLion2thNames가 생성될 때, 학생의 이름이 students에 추가된다. 학생의 이름이 String이기에 students를 선언할 때 List으로 자료형 매개변수를 지정하였다.
studentObjs 변수를 갖는다. 이 변수는 List 자료형이며, 자료형 매개변수로 Student를 갖는다. ArrayList의 객체이다.


public class LikeLion2th {
    private List<String> students= new ArrayList<>();
    private List<Student> studentObjs = new ArrayList<>();

    public LikeLion2th() {
        Names names = new Names();
        this.students = names.names();
        this.studentObjs=names.getStudetObjs();
    }

    //멋사자 2기 학생의 이름이 들어있는 list를 return하는 method
    public List<String> getStudentList(){
        return this.students;
    }

    public List<Student> getStudentObjs(){
        return this.studentObjs;
    }
}



public class ListPracticeMain {
    public static void main(String[] args) {
        LikeLion2th likeLion2th=  new LikeLion2th();
        List<String> students = likeLion2th.getStudentList();
  
  // 빈 List 객체에 정보를 호출함.
        List<Student> studentObjs = likeLion2th.getStudentObjs();


// for문 통해 List에 입력된 정보를 한 줄씩 출력.
        for(String student : students){
            System.out.println(student);
        }
        for(Student studentObj : studentObjs){
            System.out.println(studentObj.toString());
        }
        System.out.println(students.size());
    }
}
profile
작성자 개인이 잊을 때마다 보라고 정리한 글

0개의 댓글