JAVA_22_ArrayList_컬렉션

hyeong taek jo·2023년 7월 11일

JAVA

목록 보기
22/39

📌 ArrayList란?

  • 순서가 있는 데이터의 집합. 데이터의 중복을 허용한다.
  • get(), contains(), indexOf(), lastIndexOf(),size()등의 메서드가 사용된다.

📌 ArrayList 예시

ArrayList에 사용되는 일반적인 메서드

import java.util.ArrayList;

//배열보다 연산이 쉬워서 배열보다 훨씬 많이 쓰여진다.

public class ArrayList2 {
	
	public static void print(ArrayList<String> listPrint) {
		for (String str : listPrint ) {
			System.out.print(str + "\t");
		}
		System.out.println("\n----------------------------------");
	}
	
	

	public static void main(String[] args)  {
		String myString = "바나나";
		ArrayList<String> list = new ArrayList<>();
		list.add("바나나");
		list.add("수박");
		list.add("사과");
		list.add("바나나");
		list.add("수박");
		list.add("대추");
		list.add("바나나");
		System.out.println("갯수 : " + list.size());
		print(list);
     	//   0   1   2    3      4   5   6
		// 바나나	수박	사과	바나나	수박	대추	바나나
		// 1번 자리에 끼워 넣기 가능하다.
		list.add(1,"키위");
		print(list);
		list.set(4, "복숭사");
		print(list);
		list.remove(0);
		print(list);
		
		System.out.println("3번 인덱스--> " + list.get(3));
		System.out.println("바나나 문의 : " + list.contains("바나나"));
		//System.out.println("바나나 문의 indeOf : " + list.indexOf("바나나",0));
		System.out.println("바나나 문의 indexOf : " + list.indexOf("수박"));
		System.out.println("바나나 문의 : " + list.lastIndexOf("수박"));
		//HomeWork  (수박  ---> 메론 for )
		for (int i = 0 ; i < list.size(); i++) {
			if (list.get(i).equals("수박")) {
				list.set(i, "메론");
			}
		}
		print(list);
	}

}

갯수 : 7
바나나 수박 사과 바나나 수박 대추 바나나
----------------------------------
바나나 키위 수박 사과 바나나 수박 대추 바나나
----------------------------------
바나나 키위 수박 사과 복숭사 수박 대추 바나나
----------------------------------
키위 수박 사과 복숭사 수박 대추 바나나
----------------------------------
3번 인덱스--> 복숭사
바나나 문의 : true
바나나 문의 indexOf : 1
바나나 문의 : 4
키위 메론 사과 복숭사 메론 대추 바나나
----------------------------------

ArrayList에 객체를 담는 경우

import java.util.ArrayList;

public class CarEx {

	public static void main(String[] args) {
		ArrayList<Car> a1 = new ArrayList<>();
		
		a1.add(new Car());
		a1.add(new Bus());
		a1.add(new Taxi());
		// 1. print 출력
		// 2. move 출력
		
		for (Car c : a1) {
			c.print();
			// 3. move를 출력하기
			if( c instanceof Bus) {
				//아래 두줄 위 한줄 같음
				Bus b = (Bus)c;
				b.move();
				
				//한줄로
				// ((Bus)c).move();
			}
		}
	}

}

public class Car {
	void print() {
		System.out.println("난 차야");
	}
}

class Bus extends Car {
	void print() {
		System.out.println("난 Bus");
	}
	void move() {
		System.out.println("승객 50명이야");
	}
}

class Taxi extends Car {
	void print() {
		System.out.println("난 Taxi야");
	}
}

난 차야
난 Bus
승객 50명이야
난 Taxi야

profile
마포구 주민

0개의 댓글