까먹기 쉬운 ArrayList.add( Class ) 문제
--; 이런 오류를 보는게 참...하뤼레벨적인 문제인듯 한데..
Class 를 ArrayList.add()로 추가할때 발생하는 문제점(?이라기 보다는..개념무시한..) 이다.
같은 상황을 겪은 이가 올린 통해 코드를 보고서야..'아차~' 하게 되었다..ㅡ,.ㅡ
해결방안은 아래 링크에서 설명되어 있으나. 해결책은 제세되지 않기에
원문글의 코드부분을 가져와서 코드를 추가했다.
[원문글] http://coding.derkeiler.com/Archive/Java/comp.lang.java.help/2007-01/msg00317.html
I think this is a bit tougher then the last one I posted (which was quite simple). I think I'm missing something fundamental. This code runs, but when I run it and it prints out the contents of the list it shows that all items
in the list have the same value as the last item I added. I expect to see in the console:
[0] - aaa
[1] - bbb
[2] - ccc
But instead I see
[0] - ccc
[1] - ccc
[2] - ccc
------------------------------------------------------
import java.util.*;
public class Assignment1
{
public static class WordPair
{
String firstWord;
}
public static void main(String[] args)
{
WordPair tempWordPair = new WordPair();
ArrayList<WordPair> wordPairList = new ArrayList<WordPair>();
tempWordPair.firstWord = "aaa";
wordPairList.add( tempWordPair );
tempWordPair = new WordPair();
tempWordPair.firstWord = "bbb";
wordPairList.add( tempWordPair );
tempWordPair = new WordPair();
tempWordPair.firstWord = "ccc";
wordPairList.add( tempWordPair );
System.out.println("[0] - " + wordPairList.get(0).firstWord);
System.out.println("[1] - " + wordPairList.get(1).firstWord);
System.out.println("[2] - " + wordPairList.get(2).firstWord);
}
}