자바 List

오세훈·2023년 7월 24일
0

java

목록 보기
1/16

List

List 와 LinkedList의 차이

일반적인 속도는 LinkedList가 앞뒤로 연결된 데이터의 주소 정보도 같이 저장하기에 List 보다 검색 속도가 더 빠르지만

중간 삭제나 중간 삽입의 경우는 List가 더 빠르다.

List 객체 선언 및 초기화

보통 이런식으로 앞에 List를 이용하고 뒤에는 사용할 List 구조를 선택해서 초기화 하는 방식으로 사용

모든 List의 사용법은 동일하다.

List<String> lst = new ArrayList<>(); 
// List를 이용할 때 보통 이런식으로 선언해서 사용한다.

ArrayList의 값 입, 출력

package sec1;

import java.util.ArrayList;
import java.util.List;

class Student {
    private int sno;
    private String name;
    private int point;

    public Student() {}

    public Student(int sno, String name, int point) {
        this.sno = sno;
        this.name = name;
        this.point = point;
    }

    public int getSno() {
        return sno;
    }

    public void setSno(int sno) {
        this.sno = sno;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPoint() {
        return point;
    }

    public void setPoint(int point) {
        this.point = point;
    }
}

public class ListEx3 {
    public static void main(String[] args) {
        List<String> lst = new ArrayList<>(); // List를 이용할 때 보통 이런식으로 선언해서 사용한다.
        
        // 추가
        lst.add("안녕");
        lst.add("하세요");
        lst.add("하하");
        lst.add("호호");
        System.out.println(lst);
        
        // 값 또는 인덱스로 제거
        lst.remove("호호");
        lst.remove(1);
        System.out.println(lst);
        
        // 전체 값 삭제
        lst.clear();
        System.out.println(lst);

        lst.add("홍길동");
        lst.add("일지매");
        lst.add("김보경");
        lst.add("김기태");
        System.out.println(lst);
        System.out.println(lst.size()); // 개수

        // contains, list 내의 값의 존재 확인 유무
        String s = lst.contains("이기태") ? "있음" : "없음";
        System.out.println(s);
        s = lst.contains("김기태") ? "있음" : "없음";
        System.out.println(s);
        
        // list가 비워져 있는지 확인
        s = lst.isEmpty() ? "비어있음" : "채워져있음";
        System.out.println(s);

        System.out.println();
        for (int i=0; i<lst.size(); i++) {
            System.out.println(lst.get(i));
        }

        System.out.println();
        for (String i:lst
             ) {
            System.out.println(i);
        }

        // List를 클래스로 만들어서 값을 저장, 출력하는 법
        List<Student> std = new ArrayList<>();
        Student s1;
        String[] name = {"오세훈", "백준철", "신승원", "구예진"};
        for (int i=0; i<name.length; i++) {
            s1 = new Student();
            s1.setName(name[i]);
            s1.setSno(i+1);
            s1.setPoint(50);
            std.add(s1);
        }
        
        for (int i=0; i<std.size(); i++) {
            Student s2 = std.get(i);
            System.out.println(s2.getSno());
            System.out.println(s2.getName());
            System.out.println(s2.getPoint());
            System.out.println();
        }

        // jdk 1.6 이하에서는 안 될 수 있다.
        for (Student st1:std
             ) {
            System.out.println(st1.getSno());
            System.out.println(st1.getName());
            System.out.println(st1.getPoint());
            System.out.println();
        }
    }
}

ArrayList를 이용한 뱅킹 알고리즘

package sec1;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class Course {
    private int cno; // 과정 번호
    private String cName; // 코스의 이름
    private int cPrice; // 수강료
    private double cTime; // 코스의 기간

    public void setCno(int cno) {
        this.cno = cno;
    }

    public void setcName(String cName) {
        this.cName = cName;
    }

    public void setcPrice(int cPrice) {
        this.cPrice = cPrice;
    }

    public void setcTime(double cTime) {
        this.cTime = cTime;
    }

    public int getCno() {
        return cno;
    }

    public String getcName() {
        return cName;
    }

    public int getcPrice() {
        return cPrice;
    }

    public double getcTime() {
        return cTime;
    }
}
public class ListEx4 {
    // 정보를 정적으로 저장하기 위해 사용
    static List<Course> cList = new ArrayList<>();

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Course c = null;
        boolean ck = true; // 과정 작업 상태, 참이면 새로운 데이터 입력 가능, false면 서비스 종료
        int cno = 0; // 과정 수
        
        while(ck) {
            System.out.println("1 : 과정등록 | 2 : 과정검색 | 3 : 과정삭제 | 4 : 과정목록 | 5,6 : 종료");
            System.out.print("작업번호[1-6] : ");

            int num = Integer.parseInt(sc.nextLine());
            switch (num) {
                case 1: // 과정 등록
                    System.out.println("과정 등록");

                    c = new Course();
                    try {
                        System.out.printf("과목번호 : %d\n", cno);
                        c.setCno(cno);

                        System.out.print("과목이름 : ");
                        String s1 = sc.nextLine();
                        c.setcName(s1);

                        System.out.print("단가 : ");
                        int i1 = Integer.parseInt(sc.nextLine());
                        c.setcPrice(i1);

                        System.out.print("소요시간 : ");
                        double d = Double.parseDouble(sc.nextLine());
                        c.setcTime(d);

                        cno++;
                        System.out.printf("과목번호 : %d\n", cno);
                        c.setCno(cno);

                        cList.add(c);
                        System.out.println("새로운 과정을 등록하였습니다.");

                    } catch (Exception e) {
                        System.out.println("입력 오류 발생");
                    } finally {

                    }
                    break;
                    
                case 2: // 과정 검색
                    System.out.println("과정 검색");
                    System.out.println("검색할 과정 번호 : ");
                    int no = Integer.parseInt(sc.nextLine());
                    if (no<=num) {
                        Course co = cList.get(no);
                        System.out.printf("과정번호 : %d\n",co.getCno());
                        System.out.printf("과정이름 : %s\n",co.getcName());
                        System.out.printf("과정단가 : %d\n",co.getcPrice());
                        System.out.printf("소요시간 : %f\n",co.getcTime());
                    } else {
                        System.out.println("해당 과정이 존재하지 않습니다.");
                    }
                    System.out.println();
                    break;
                    
                case 3: // 과정 삭제
                    System.out.println("과정삭제");
                    System.out.print("삭제할 과정 번호: ");
                    no = Integer.parseInt(sc.nextLine());
                    if (no<=num) {
                        cList.remove(no);
                    } else {
                        System.out.println("해당 과정이 존재하지 않습니다.");
                    }
                    break;

                case 4: // 과정목록
                    System.out.println("과정 목록");
                    for(Course c1:cList) {
                        System.out.printf("과정번호 : %d\t",c1.getCno());
                        System.out.printf("과정이름 : %s\t",c1.getcName());
                        System.out.printf("과정단가 : %d\t",c1.getcPrice());
                        System.out.printf("소요시간 : %f\t",c1.getcTime());
                        System.out.println();
                    }
                    break;

                case 5:
                case 6:
                    ck = false;
                    break;

                default:
                    System.out.println("작업 번호는 1~6까지 입니다.");
            }
            c = new Course();
        }
        

    }
}

Vector를 이용한 List

package sec1;

import java.util.List;
import java.util.Vector;

class Qna {
    private int qno;
    private String title;
    private String contents;

    public Qna(int qno, String title, String contents) {
        this.qno = qno;
        this.title = title;
        this.contents = contents;
    }

    public int getQno() {
        return qno;
    }

    public void setQno(int qno) {
        this.qno = qno;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContents() {
        return contents;
    }

    public void setContents(String contents) {
        this.contents = contents;
    }
}

public class ListEx5 {
    public static void main(String[] args) {
        List<Qna> q = new Vector<>();
        for (int i=1; i<10; i++) {
            q.add(new Qna(i, "제목"+i, "내용"+i));
        }
        for (Qna q1: q
             ) {
            System.out.printf("%d %s %s\n",q1.getQno(), q1.getTitle(), q1.getContents());
        }
    }
}

LinkedList 이용

package sec1;

import java.util.LinkedList;
import java.util.List;

public class ListEx6 {
    public static void main(String[] args) {
        List<Student> s = new LinkedList<>();
        String[] name = {"오세훈", "백준철", "신승원", "구예진"};
        for (int i=0; i<4; i++) {
            int num = i+1;
            s.add(new Student(num, name[i], num<<2));
        }
        for (Student s1: s) {
            System.out.printf("%d %s %d\n", s1.getSno(), s1.getName(), s1.getPoint());
        }
    }
}
profile
자바 풀 스택 주니어 개발자

1개의 댓글

comment-user-thumbnail
2023년 7월 24일

유익한 글이었습니다.

답글 달기