Please Enable JavaScript!
Mohon Aktifkan Javascript![ Enable JavaScript ]

제너릭

2010. 3. 19. 00:07programming/jsp

728x90
 
u제네릭 프로그래밍
(generic programming)
n일반적인 코드를 작성하고 코드를 다양한 타입의 객체에 대하여
재사용하는 프로그래밍 기법 n제네릭은 컬렉션 라이브러리에
많이 사용, n매개변수 타입은 클래스 (참조형) 사용


public class GenericTest {
 public static void main(String args[]){
  Store<String> store = new Store<String>();
  //문자열 타입 저장
  
  store.set("Generic");
  String str=(String)store.get();
  System.out.println(str);
  // store.set(new Integer(100)); // 정수 타입을 저장하려고 하면 컴파일 오류
  
 }
}

 
u문자열을 저장하려면 다음과 같이 선언
nStore<String> store = new Store<String>();
u정수를 저장하려면 다음과 같이 선언
nStore<Integer> store = new Store<Integer>();


 
List 인터페이스 - ArrayList
ArrayList를 배열(Array)의 향상된 버전
또는 가변 크기의 배열이라고
생각하면 된다.

ArrayList의 생성
nArrayList<String> list = new ArrayList<String>();
원소 추가
nlist.add( "MILK" );      
nlist.add( "BREAD" );      
nlist.add( "BUTTER" );

===================
 
ArrayList 사용 예제

=====================
 
import java.util.*;
public class ArrayListExample3 {
    public static void main(String args[]) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("머루");           
        list.add("사과");          
        list.add("앵두");      
        list.add("자두");      
        list.add("사과");        
        int index1 = list.indexOf("사과"); //"사과"데이터의 저장 위치 반환
        int index2 = list.lastIndexOf("사과");
//리스트 마지막부터 원소 위치검색
        System.out.println("첫번째 사과: " + index1);
        System.out.println("마지막 사과: " + index2);
    }
}
728x90