Non-generic ArrayList
nongeneric ArrayList 객체 yourList를 선언하고 다른 타입인 3개의 객체들을 저장한다.
ArrayList yourList = new ArrayList(); yourList.add(new Integer(35)); //Integer yourList.add(new String("bunny")); //String yourList.add(new Double(3.14)); // Double
아래의 문장은 오류가 일어난다. 문자열 변수의 타입을 정해주지 않았기 때문이다.
String animal = yourList.get(1);
String 타입으로 참조해야 한다.
String animal = (String) yourList.get(1);
요소 1이 String 타입이어야만 참조할 수 있다. 다음 문장은 컴파일은 되지만 오류가 난다. 왜냐하면 요소 2는 Double 객체를 참조하기 때문이다.
String animalTwo = (String) yourList.get(2);
예시)
import javax.swing.*; import java.util.*; public class Ex_2_2_P67 { public static void main(String[] args) { ArrayList yourList = new ArrayList(); yourList.add(new Integer(35)); //Integer yourList.add(new String("bunny")); //String yourList.add(new Double(3.14)); // Double int n = yourList.size(); JOptionPane.showMessageDialog(null, n); for (int i = 0; i < n; i++) System.out.print(yourList.get(i) + "\t"); System.out.println("n = " + n); Integer animal = (Integer)yourList.get(0); String animal2 = (String)yourList.get(1); Double animal3 = (Double)yourList.get(2); System.out.println(animal + "\t" + animal2 + "\t" + animal3); } }
'DATA STRUCTURES' 카테고리의 다른 글
The LinkedList Class (0) | 2014.10.16 |
---|---|
Applications of ArrayList (0) | 2014.10.16 |
The ArrayList Class (0) | 2014.10.09 |
Converting Numeric String to Numbers (0) | 2014.10.09 |
Arrays (0) | 2014.10.09 |