//////
Search
🍒

[1005] Class, interface, 의존관계(DI), Collection-List

생성일
2022/11/10 07:58
태그
TodayILearn
java
생성일 1

Class

Method와 Class

class와 main()의 관계가 이해하기 어려운 이유는 무엇일까?
1.
모든 메소드(함수)와 필드(변수)는 클래스 안에 들어가 있기 때문
2.
자기 자신에서 자기 자신을 실행하는 것 처럼 보이기 때문
방법 1. main함수에 객체 생성
MyList 클래스의 인스턴스 변수/ 인스턴스메소드를 main에서 사용하려고 한다면 객체를 생성해야 인스턴스 변수와 함수에 접근 가능!
방법2. static 메소드로 변경
MyList 클래스 중 쓰려고 한 인스턴스 메소드에 static을 붙여 클래스 메소드로 변경한다.
이렇게 하면 객체 생성 없이도 main() 안에서 사용이 가능!

Class가 필요한 이유

클래스는 데이터와 함수의 결합입니다.
기능적으로 본다면, 연산(함수)에 필요한 데이터를 클래스로 묶기 때문에
서로 관련된 값들을 강하게 묶을 수 있고, 코드가 간단하고 유지 보수가 편리합니다.
사칙연산 코드
public class Calculator { private int a; private int b; public Calculator(int a, int b) { this.a = a; this.b = b; } public void plus() { System.out.println(a + b); } public void minus() { System.out.println(a - b); } public void multiple() { System.out.println(a * b); } public void divide() { System.out.println((double)a / b); } }
Java
복사
Main함수
값을 한 번만 넣고 위의 함수에 따라 여러가지 연산을 할 수 있습니다.
public class CalculatorMain { public static void main(String[] args) { Calculator c = new Calculator(1, 2); c.plus(); c.minus(); c.multiple(); c.divide(); } }
Java
복사

컬렉션 프레임워크 (collection framework)와 리스트(list)

자료구조

프로그램을 개발할 때 자료를 어떻게 다룰 것인지 고민해야 한다. 자료를 활용하는 방식에 따라 프로그램의 성능이 달라질 수 있다.
자료구조(data structure)는 효율적인 접근 및 수정을 가능하게 하는 자료의 조직, 관리, 저장 등을 의미한다.
자바에서는 필요한 자료 구조를 미리 구현하여 java.util 패키지에서 제공하는데, 이를 컬렉션 프레임워크(collection framework)라고 한다.

자바 컬렉션 프레임워크

자바 컬렉션 프레임워크에는 여러 인터페이스가 정의되어 있고, 그 인터페이스를 구현한 클래스들이 있다.
컬렉션 프레임워크의 계층도는 위와 같으며, 그림 외에도 다양한 자료구조가 구현되어 있다.
Collection 프레임워크의 대표적인 두 인터페이스는 Collection 인터페이스와 Map 인터페이스이다.
Collection 인터페이스는 하나의 자료를 모아서 관리하는데 필요한 기능을 제공한다.
Map 인터페이스는 쌍(pair)으로 된 자료를 관리하는데 필요한 기능을 제공한다.

Collection 인터페이스의 메소드

Collection 인터페이스에 선언된 메소드 중 다음과 같은 메소드가 자주 사용된다.
boolean add(E e) : Collection에 객체를 추가한다.
void clear() : Collection의 모든 객체를 제거한다.
boolean remove(Object o) : Collection에 매개변수에 해당하는 인스턴스가 존재하면 제거한다.
int size() : Collection에 있는 요소의 개수를 반환한다.

List 인터페이스

List 인터페이스는 대표적으로 ArrayList, LinkedList, Vector, Stack 등의 클래스에서 구현되어 있다.
List 인터페이스는 순서가 있는 자료를 관리할 때 주로 쓰인다.
중복이 허용된다.

실습

실습 1

멋쟁이사자처럼2기의 모든 학생의 이름을 List에 추가하고, 이름을 출력해보자.

1. 이름을 넣어둘 List가 있는 Class를 만들자.

import java.util.ArrayList; import java.util.List; public class LikeLion2thNames { private List<String> students = new ArrayList<>(); //설명 1 public LikeLion2thNames() { //설명 2 this.students.add("강동연"); this.students.add("강수빈"); this.students.add("권하준"); this.students.add("조성윤"); //...(생락) this.students.add("권유겸"); this.students.add("강서현"); this.students.add("문찬율"); this.students.add("한도현"); } public List<String> getNameList(){ //설명 3 return students; } }
Java
복사
LikeLion2thNames 클래스를 정의하였다.
1.
이 클래스의 멤버변수는 students 이다. List<String> 자료형이며, List 인터페이스의 하위 객체인 ArrayList<>()로 인스턴스를 생성하였다. ArrayList<>는 일반적인 배열과 달리 동적으로 배열 크기를 조정한다. 따라서 배열의 크기를 신경쓰지 않아도 된다.
2.
LikeLion2thNames의 생성자이다. LikeLion2thNames가 생성될 때, 학생의 이름이 students에 추가된다. 학생의 이름이 String이기에 students를 선언할 때 List<String>으로 자료형 매개변수를 지정하였다.
3.
List<String>을 반환하는 메소드이다. 학생들의 이름이 저장된 ArrayList students를 반환한다.

2. List를 불러올 Class를 만들자.

import java.util.List; public class LikeLion2th { private LikeLion2thNames names = new LikeLion2thNames(); //1 private List<String> students; public LikeLion2th() { //2 students = names.getNameList(); } public List<String> getStudentList() { //3 return this.students; } }
Java
복사
LikeLion2th 클래스를 정의하였다.
1.
LikeLion2th 클래스의 멤버변수는 names와 students이다.
names는 LikeLion2thNames의 객체이다.
studens는 List<String> 자료형이다.
2.
LikeLion2th의 생성자이다. LikeLion2th가 생성될 때 students 변수에 names.getNameList() 메소드가 호출된다. 이 메소드를 통해 students 변수는 학생들의 이름이 담긴 ArrayList 객체의 주소를 가리키게 된다.
3.
List<String>을 반환하는 메소드이다. 학생들의 이름이 담긴 ArrayList 객체를 반환하는 역할을 한다.

3. Main Class에서 학생들의 이름을 출력하자.

import java.util.List; public class LikeLion2thMain { public static void main(String[] args) { LikeLion2th likeLion2th = new LikeLion2th(); //1 List<String> students = likeLion2th.getStudentList(); //2 for (String student : students) { //3 System.out.println(student); } System.out.println(students.size()); //4 } }
Java
복사
Main 클래스에 main 함수를 통해 실행하였다.
1.
likeLion2th 는 LikeLion2th의 객체이다. likeLion2th를 참조하여 LikeLion2th 클래스 내부의 메소드와 멤버변수에 접근할 수 있다.
2.
List<String>자료형인 students 변수에 학생들의 이름이 담긴 ArrayList<> 객체를 담았다. ArrayList<> 객체를 담기 위해 likeLion2th.getStudentList() 메소드를 호출하였다. 해당 메소드는 LikeLion2th 내부의 ArrayList 객체가 담긴 students를 반환한다.
3.
students에 학생들의 이름이 담긴 ArrayList 객체가 있으므로, for each 구문으로 각 학생의 이름을 출력하였다. 이때 student는 toString 메소드를 거쳐서 나온다.
4.
students의 배열 길이를 출력한다.

실습 2

멋쟁이사자처럼2기 학생의 반, 이름, 깃허브 주소를 List에 추가하고, 이름을 출력해보자.

1. 학생의 속성을 멤버변수로 갖는 Class를 만들자.

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; } @Override public String toString() { return "소속 : "+ classNo + "반, 이름 : " + name + ", repo : " + gitRepositoryAddress; } }
Java
복사
이전 실습과 다르게 하나의 자료형으로 세 가지 변수를 저장할 수 없다. 따라서 새로운 클래스를 정의하고 이를 참조자료형으로 활용해야 한다. 따라서 Student 객체를 생성하였다.
이 클래스는 학생의 반, 이름, 깃허브 주소를 멤버변수로 갖는다.
객체가 출력될 때는 소속, 이름, repo를 출력할 수 있게 toString() 메소드를 재정의하였다.

2. 학생의 속성을 넣어둘 List가 있는 Class를 만들자.

import java.util.ArrayList; import java.util.List; public class LikeLion2thNames { private List<Student> studentObjs = new ArrayList<>(); //1 public List<Student> getStudentObjs() { //2 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")); this.studentObjs.add(new Student(2,"최경민","https://github.com/cmkxak/likelion-java-course")); return studentObjs; } }
Java
복사
LikeLion2thNames 클래스를 정의하였다.
1.
LikeLion2thNames 클래스는 studentObjs 변수를 갖는다. 이 변수는 List 자료형이며, 자료형 매개변수로 Student를 갖는다. ArrayList의 객체이다.
2.
List<Student>를 반환하는 메소드이다. 학생의 속성을 추가하고, 동시에 반환하는 역할을 한다. 학생의 속성을 추가할 때는 Student 객체가 생성되며, Student 객체의 생성자에 따라 학생의 속성이 입력되어야 한다.

3. List를 불러올 Class를 만들자.

import java.util.List; public class LikeLion2th { private LikeLion2thNames names = new LikeLion2thNames(); private List<Student> studentObjs; public LikeLion2th() { studentObjs = names.getStudentObjs(); } public List<Student> getStudentObjsList() { return this.studentObjs; } }
Java
복사
LikeLion2th 클래스를 생성하였다. 실습 1의 2번과 동일하게 동작한다.

4. Main Class에서 학생들의 속성을 출력하자.

import java.util.List; public class LikeLion2thMain { public static void main(String[] args) { LikeLion2th likeLion2th = new LikeLion2th(); List<Student> studentObjs = likeLion2th.getStudentObjsList(); for (Student studentObj : studentObjs) { System.out.println(studentObj); } System.out.println(studentObjs.size()); } }
Java
복사
실습 1의 3번과 동일하게 동작한다.