데이터 과학

ArrayList 예제 본문

AP/AP Computer Science A

ArrayList 예제

티에스윤 2024. 1. 12. 17:17

다음은 ArrayList와 List, 제네릭에 대한 예제입니다. 

 

이 예제에서는 add(), get(), remove(), for~each에 대한 내용을 가지고 있습니다. 

 

한번 실행해 봅시다. 

 

 

 

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
public class ListExample {
    public static void main(String[] args) throws InterruptedException {
 
        List<String> listA = new ArrayList<String>();
 
        listA.add("푸바오");
        listA.add("제니퍼");
        listA.add("달님");
        listA.add(new String("달랫"));
        listA.add(1, "tsyoon");
       
        System.out.println(listA);
 
 
        // 인덱스를 통한 조회
        String element0 = listA.get(0);
        String element1 = listA.get(1);
        String element3 = listA.get(2);
 
        //Iterator 통한 전체 조회
        Iterator<String> iterator = listA.iterator();
        while (iterator.hasNext()) {
            String element = iterator.next();
            System.out.println(element);
        }
 System.out.println();
        //for-loop 통한 전체 조회
//        for(Object object : listA) {
 //           String element = (String) object;
  //      }
 
 
        // 삭제하기
        //System.out.println(listA.remove(0));
       System.out.println(listA.remove("달랫"));
 
     // 존재 여부를 확인하고 싶을 때
       System.out.println(listA.contains("달랫"));
        System.out.println();
       
   for(Object object : listA) {
            String element = (String) object;
            System.out.println(object);
   }
   System.out.println();
         int index = listA.indexOf("tsyoon");
        listA.add(index, "값 추가");
   
   
     for(Object object : listA) {
            String element = (String) object;
            System.out.println(object);
   }
   
    }
}

 

 

 

결과: 

 

[푸바오, tsyoon, 제니퍼, 달님, 달랫]
푸바오
tsyoon
제니퍼
달님
달랫

true
false

푸바오
tsyoon
제니퍼
달님

푸바오
값 추가
tsyoon
제니퍼
달님

 

'AP > AP Computer Science A' 카테고리의 다른 글

this와 toString() 메소드  (0) 2024.05.29
static 변수  (0) 2024.05.29
생성자 선언 관련 문제  (1) 2024.01.11
Blue J 설치  (0) 2024.01.07
super 예제  (1) 2024.01.05