자바 List,ArrayList,소트에대해 질문드립니다.

Question:

안녕하세요. 17살부터 자바웹프로그래머를꿈꾸고온 18살 홍승민이라합니다.

다만 제가지금 자바공부를하면서 List종류에막혔거든요.

그래서 질문드립니다. 답장꼭해주세요ㅠ.ㅠ

1.

List list = new ArrayList(); 와

ArrayList list = new ArrayList(); 는 뭐가 다른것인가요?

2.

List list = new ArrayList(); 와

List list = new ArrayList(); 는 뭐가다른것인가요?

  1. 소스질문드립니다.

성적관리 프로그램을 만들고 있는데 소트에서 막혔습니다.

총점에따라 성적을 나누려고하는데요.

이름 국어 영어 총점

홍 100 10 110

승 100 90 190

민 100 100 200

로 입력한다면

이름 국어 영어 총점

민 100 100 200

승 100 90 190

홍 100 10 110

이렇게 소트하고싶은데, 도저희 어디서부터 소트를해야하며 어디서부터 소트를만들어야하는지 모르겠습니다.

class Student
{
    String name;
    double total;
    double avg;
    double[] score;
    public Student(String name,double[] score)
    {
        this.name = name;
        this.score = score;
    }
    public void list()
    {
        calculateTotal();
        calculateAverage();
        System.out.print(name+"t");
    for(int x = 0;x < score.length;x++)
    {
        System.out.print(score[x]+"t");
    }
    System.out.print(total+"t");
    System.out.print(avg);

    }
    public void calculateTotal()
    {
        for(int x = 0;x < score.length;x++)
        {
            total += score[x];
        }
    }
    public void calculateAverage()
    {
        avg = total/score.length;
    }

}

import java.io.*;
import java.util.*;

public class Exam_01
{
public static void main(String[] ar) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
ArrayList list = new ArrayList();
System.out.print("과목 겟수 :: ");
int sub = Integer.parseInt(in.readLine());
String[] subject = new String[sub];

for(int x = 0;x < subject.length;x++)
{
System.out.print(x+1+"번 과목의 이름 :: ");
String s = in.readLine().toString();
subject[x] = s;
}
System.out.print("학생 수 :: ");
int stu = Integer.parseInt(in.readLine());
int i = 0;
for(int x = 0;x < stu;x++)
{
System.out.print(x+1+"번 학생의 이름 :: ");
String name = in.readLine().toString();
double[] sco = new double[sub];
for(int z = 0;z < subject.length;z++)
{
boolean test = false;
while(!test)
{
System.out.print(subject[z]+" 과목의 점수 :: ");
double score = Double.parseDouble(in.readLine());
if(score 100)
{
System.out.println("0보다작거나 100보다 큽니다. 다시입력해주세요.");
test = false;
}
else
{
sco[x] = score;
test = true;
}
}
}
Student data = new Student(name,sco);
list.add(data);
}
System.out.print("이름"+"t");
for(int y = 0; y < subject.length;y++)
{
System.out.print(subject[y]+"t");
}
System.out.print("총점t평균");
System.out.println();
for(int x = 0;x < stu;x++)
{
Student target = (Student)list.get(x);
target.list();
System.out.println();
}
}
}

입니다.

무엇을서야하며 어디서 고쳐야하는지 , 답을 알려주시면 감사드리겠습니다.

부탁드립니다

Answer:

1.

List list = new ArrayList(); 와

ArrayList list = new ArrayList(); 는 뭐가 다른것인가요?

간단하게 예를 들어 설명하도록 하겠습니다.

List list = new ArrayList() 는

도형 list = new 정사각형();

ArrayList list = new ArrayList();

정사각형 list = new 정사각형();

위의 예처럼 List는 interface입니다. 인터페이스는 공통되는 메소드를 추출해놓은 클래스로 생각하시면 됩니다. 클래스를 생성할때 도형 타입으로 생성하게 되면 정사각형이 아닌 다른 직사각형, 삼각형등 도형 인터페이스를 구현한 클래스에서 사용 될 수 있습니다. 그렇지만 정사각형 클래스로 생성하게 되면 직사각형, 삼각형등에서는 사용할 수 없게 됩니다. 자바의 특징중 다형성을 참조 하십시오.

2.

List list = new ArrayList(); 와

List list = new ArrayList(); 는 뭐가다른것인가요

이 부분은 위와 비슷한 부분인데 간단하게 List에 담겨질 객체의 타입을 정해 준 겁니다. 기본적으로 자바의 Collection 은 Object 타입으로 추가가 됩니다.

List list = new ArrayList();

Object obj = list.get(1); // 이런식으로 Object 타입으로 리턴이 됩니다.

그렇지만

List list = new ArrayList<Student)();

Student stu = list.get(1); // 이런식으로 return 타입이 Student 객체로 출력 됩니다.

그리고 타입을 설정하게 되면 Student 객체가 아닌 다른 타입은 add를 할 수 없기 때문에

오류를 예방 할 수 있습니다.

  1. 코드 수정 및 정렬
    저는 BufferedInputStream이 아닌 Scanner를 사용해서 작성했습니다.

형변환을 피하기 위해서 변경 해봤습니다. 붉게 표시된 부분이 질문자님의 코드와

다른 부분입니다.

  • score[x] = score 로 사용하셨는데 x변수는 학생 수를 의미 하므로 z로 변경 해주셔야 합니다.

  • Collections.sort(list, new StudentComparator());

이 부분은 리스트를 정렬하기 위해 사용합니다. 뒤에 있는 StudentComparator() 클래스를 정렬할 기준을

정해주기 위해 사용했습니다.

예를 들어

int a = 0;

int b = 1;

위와 같이 정수형 변수 a,b 에서는 어떤것이 크고 작다를 알 수 있습니다.

그렇지만 Student 클래스 a,b 를 비교하기 위해서 기준을 알 수 없습니다. 국어 과목을 기준으로 정렬할 것인지 수학을 기준으로 정렬할 것인지 총점으로 정렬할 것인지…

그래서 기준을 정의 하기 위해 작성했습니다.

package sort;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

public class Exam_01 {

    public static void main(String[] ar) throws IOException {
        Scanner scanner = new Scanner(System.in, "euc-kr");
//        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        ArrayList list = new ArrayList();

        System.out.print("과목 겟수 :: ");
        int sub = scanner.nextInt();
//        int sub = Integer.parseInt(in.readLine());
        String[] subject = new String[sub];

//        for (int x = 0; x < subject.length; x++) {
//            System.out.print(x + 1 + "번 과목의 이름 :: ");
//            String s = in.readLine().toString();
//            subject[x] = s;
//        }
        System.out.println("과목명을 입력하세요.");

        for(int i=0; i<sub; i++) {
            subject[i] = scanner.next();
        }



        System.out.print("학생 수 :: ");
//        int stu = Integer.parseInt(in.readLine());
        int stu = scanner.nextInt();
        int i = 0;
        for (int x = 0; x < stu; x++) {
            System.out.print(x + 1 + "번 학생의 이름 :: ");
//            String name = in.readLine().toString();
            String name = scanner.next();
            double[] sco = new double[sub];
            for (int z = 0; z < subject.length; z++) {
                boolean test = false;
                while (!test) {
                    System.out.print(subject[z] + " 과목의 점수 :: ");
//                    double score = Double.parseDouble(in.readLine());
                    double score = scanner.nextDouble();
                    if (score  100) {
                        System.out.println("0보다작거나 100보다 큽니다. 다시입력해주세요.");
                        test = false;
                    } else {
                        sco[z] = score; // x는 학생 수 이므로 z로 변경 필요
                        test = true;
                    }
                }
            }
            Student data = new Student(name, sco);
            list.add(data);
        }

        System.out.print("이름" + "t");
        for (int y = 0; y < subject.length; y++) {
            System.out.print(subject[y] + "t");
        }
        Collections.sort(list, new StudentComparator());

        System.out.print("총점t평균");
        System.out.println();


        for (int x = 0; x < stu; x++) {
            Student target = (Student) list.get(x);
            target.list();
            System.out.println();
        }
    }
}

class Student {

    String name;
    double total;
    double avg;
    double[] score;

    public Student(String name, double[] score) {
        this.name = name;
        this.score = score;
    }

    public void list() {
        calculateTotal();
        calculateAverage();


        System.out.print(name + "t");
        for (int x = 0; x < score.length; x++) {
            System.out.print(score[x] + "t");
        }
        System.out.print(total + "t");
        System.out.print(avg);



    }

    public void calculateTotal() {
        for (int x = 0; x < score.length; x++) {
            total += score[x];
        }
    }

    public void calculateAverage() {
        avg = total / score.length;
    }
}


/**
 * Student 클래스를 비교 하기 위한 비교 조건
 */
class StudentComparator implements Comparator {

    @Override
    public int compare(Student student1, Student student2) {
        // 총점이 높은 사람을 조건으로 하여 정렬하도록 합니다.
        if(student1.total >= student2.total) {
            return 1;
        } else {
            return 0;
        }

    }

}

답글 남기기

아래 항목을 채우거나 오른쪽 아이콘 중 하나를 클릭하여 로그 인 하세요:

WordPress.com 로고

WordPress.com의 계정을 사용하여 댓글을 남깁니다. 로그아웃 /  변경 )

Facebook 사진

Facebook의 계정을 사용하여 댓글을 남깁니다. 로그아웃 /  변경 )

%s에 연결하는 중