마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

ArrayList <T> 로 리턴된 함수 복사 왜 안되나요?

0 추천

메인

ArrayList<Student> save = null;

save = copyStudent();

 

class Student{

       String name;

       int age;

      Studnet(String name, int age){
            this.name = name;
            this.age= age 

       }

 class ArrayList<Student> copyStudent(){
         ArrayList<Student> temp = null

         Student sTemp;

         sTemp = new Studnet("홍길동", "20"); temp.add(sTemp);

        retrun temp;

}

 

소스는 대충 이런식으로 되고 있습니다.

ArrayList 를 배우면서 새롭게 만들어서 사용하려고하는데

그런데 메인클레스에서 ArrayList 복사(save = copyStudent();)에서 오류가 생깁니다..

정의된 함수에서 같은 형식의 ArrayList<T> 로 리턴이 되는데 왜 그러는걸까요?

 

말복이a (160 포인트) 님이 2013년 3월 7일 질문

2개의 답변

+1 추천

대충 설명하시니 보이는 소스대로만 대충 답변하자면

class ArrayList<Student> copyStudent(){
         ArrayList<Student> temp = null

         Student sTemp;

         sTemp = new Studnet("홍길동", "20"); temp.add(sTemp);

        retrun temp;

}

 

 

temp.add(sTemp);

하기전에 객체를 생성하셔야될듯

 

ArrayList<Student> temp = null

이 아니라 

 

ArrayList<Student> temp = new ArrayList<Sutudent>();

 

익명사용자 님이 2013년 3월 7일 답변
0 추천

Null Pointer Exception 나올거 같은 소스네요.

그리고 메소드가 아니고 클래스로 구현되있네요 ㄷㄷ.. 저는 일단 메소드 형식으로 바꿔서 알려드릴게요.

2가지 방법을 제시 해드릴 수 있는데 원하는 방향으로 구현해보세요.

 

1안 먼저 arrlist를 만든 후 그곳에 데이터만 채워넣는다.

 

private ArrayList<Student> copyStudent(ArrayList<Student> arrList){
         ArrayList<Student> temp = arrList;

         Student sTemp;

         sTemp = new Studnet("홍길동", "20");

         temp.add(sTemp);

        retrun temp;

}

 

2안 새로운 리스트를 만들어 데이터를 넣는다

 

private ArrayList<Student> copyStudent(){
         ArrayList<Student> temp = new ArrayList<Student>();

         Student sTemp;

         sTemp = new Studnet("홍길동", "20"); 

         temp.add(sTemp);

        retrun temp;

}

개인적으로는 1안을 주로 사용합니다.

 
dev_아마 (9,750 포인트) 님이 2013년 3월 7일 답변
...