본문 바로가기
Collection/ArrayList

ArrayList(2)

by pms93 2022. 7. 22.

 

package arrayLists;

import java.util.ArrayList;

public class ArrayList2 {

	public static void main(String[] args) {

		// ArrayList의 기능
		ArrayList list = new ArrayList();
		
		
		// .add(데이터); 
		// - ArrayList에 데이터를 저장한다. - 배열과 같이 index(0)부터 저장된다.
		list.add("123");
		list.add("456");
		list.add("123");
		list.add("789");
		
		
		// .get(index); 
		// - 해당하는 index에 담긴 데이터를 반환한다.
		System.out.println("list[0] : " + list.get(0));
		System.out.println("list[1] : " + list.get(1));

		
		// .contains() 
		// - 파라미터에 입력된 데이터와 동일 데이터가 있는지 확인이 가능하며 true 혹은 false의 결과를 반환한다.
		System.out.println(list.contains("123"));
		System.out.println(list.contains("456"));
		System.out.println(list.contains("79"));
		
		
		// .size() 
		// - 저장된 ArrayList의 크기(데이터 개수)를 반환한다.
		System.out.println("list에 보관된 데이터 개수 : " + list.size());
		
		
		// .indexOf() 
		// - 파라미터와 동일한 데이터가 존자한다면 해당 index를 반환한다. 
		// - 일치하는 데이터가 존재하지 않을 시 -1을반환한다. 
		// - 일치하는 데이터가 2개 이상일 경우 처음 마주치는 데이터의 index를 반환한다. 
		// .lastIndexOf() 
		// - 파라미터와 동일한 데이터의 가장 마지막 index를 반한다. 
		// - 일치하는 데이터가 존재하지 않을 시 -1을 반환한다.
		System.out.println(list.indexOf("123"));
		System.out.println(list.indexOf("456"));
		System.out.println(list.indexOf("12"));
		System.out.println(list.lastIndexOf("123"));

	
		// .remove
		// - 데이터를 삭제하는 기능이다. 삭제된 데이터 이후의 배열에 데이터가 존재한다면 자리를 한칸씩 당겨온다. 
		// - 더블쿼터, index, 입력된 값을 통해 데이터를 삭제할 수 있다.
		// - 더블쿼터, 입력된 값을 통한 데이터 삭제의 결과는 true, false로 반환해준다.
		// - index를 통한 데이터 삭제는 삭제되는 데이터를 반환해준다.
		// .clear()
		// - ArrayList에 존재하는 모든 데이터를 삭제한다.
		System.out.println("데이터 삭제 후 결과 : " + list.remove("123"));
		System.out.println("데이터 삭제 후 결과 : " + list.remove(2));
		System.out.println("데이터 삭제 후 list : " + list);
		list.clear();
		System.out.println(".clear()이후 list : " + list);
		
		
		// .isEmpty()
		// - 데이터의 존재 유무를 true, false로 반환한다.
		System.out.println(list.isEmpty());
		list.add("123");
		list.add("456");
		System.out.println(list.isEmpty());
		
		
		// .set(index, element), .add(index, element)
		// - set은 해당 index의 데이터를 element로 변경한다.
		// - 변경 전 데이터(oldValue)를 반환한다.
		// - add는 해당 index에 element를 삽입한 후 이후의 기존 데이터들을 뒤로 나열한다.
		System.out.println(list);
		list.add(1, "234");
		System.out.println(list);
		list.set(1, "248");
		System.out.println(list);
	}
}

'Collection > ArrayList' 카테고리의 다른 글

ArrayList 예제(2)  (0) 2022.07.25
ArrayList 예제(1)  (0) 2022.07.24
ArrayList(1)  (0) 2022.07.22