728x90

ArrayList는 배열과 리스트의 특징을 둘다 가지고 있는 클래스이다.
원래의 배열은 크기를 지정해주고 값을 넣어주기 때문에 새로운 값을 넣으면 크기가 초과되어 오류가 난다.

하지만 ArrayList는 처음부터 크기를 정해주는 방식이 아니라
넣는 데이터의 갯수에 따라 크기가 가변적으로 바뀌기 때문에 배열의 한계를 해결해주는 편리한 클래스이다.

 

ArrayList 라는 자바에서 만들어준 클래스를 사용하는 방법은

ArrayList list = new Arraylist();

라고 선언해 주고 

list.add();
list.get();

이렇게 사용하면 된다.

그리고 필드와 메소드를 담아놓은 클래스를 상속? 받아 ArrayList를 사용할 때에는

ArrayList<클래스이름> list = new ArrayList<>(); 


이런 양식으로 선언을 해 주어야 한다.

일단 필요한 필드와 메소드를 선언한 Car 클래스를 만들고

package day0916;
//설계도인 이 클래스 안에서 필드의 초기값은 없다.

import java.text.DecimalFormat;

public class Car {
		
	//필드
	//차량번호
	private String number, color, type;
	//차량 종류
	//private String type;
	//연식
	private int year, price;
	//가격
	//private int price;
	//색깔
	//private String color;
	
	
	//파라미터가 있는 생성자
	public Car(String number, String type, int year, int price, String color) {
		//number = number; 
		//이렇게 하면 number는 윗줄에 있는 파라미터 = 파라미터가 되서 입력?이 안된다
		//우리가 원하는건 Car 클래스 안의 필드 number에 파라미터 값을 입력하고 싶은거니까 
		//클래스안의 필드를 가리키는this를 해줘야 한다.
		this.number = number;
		this.type = type;
		this.year = year;
		this.price = price;
		this.color = color;
	}
	
	//필드에 대한 캡슐화
	public void setNumber(String number) {
		this.number = number;
	}
	public String getNumber() {
		return number;
	}
	
	public void setType(String type) {
		this.type = type;
	}
	public String getType() {
		return type;
	}
	
	public void setYear(int year) {
		this.year = year;
	}
	public int getYear() {
		return year;
	}
	
	public void setPrice(int price) {
		this.price = price;
	}
	public int getPrice(){
		return price;
	}
	
	public void setColor(String color) {
		this.color = color;
	}
	public String getColor() {
		return color;
	}
	public String toString() { 
		//이게 없으면 다른 클래스에서 클래스명[i]로 출력하면 원하는 값이 아니라 주소값이 출력된다. 
		//Car의 객체가 들어있는 이 클래스안에 toString을 선언해 줘야 우리가 원하는 값이 출력.
		
		return "차량번호: " +number+
				", 차량종류: "+type+
				", 차량가격: "+price+"원"+
				", 차량연식: "+year+"년"+
				", 차량색상: "+color;
	}
	
	
	
	
}

 메인메소드에서 이렇게 사용하면 된다.

package day0918;

import java.util.ArrayList;

import day0916.Car;

public class Ex01ArrayList {

	public static void main(String[] args) {
		//어레이리스트 선언하기
		ArrayList<Car> carList = new ArrayList<>();
		//어레이리스트가 어디를 참조해야 하는지 정해주는 코드
		Car c1 = new Car("a", "typeA", 2000, 100000, "a");
		Car c2 = new Car("b", "typeB", 2001, 200000, "b");
		Car c3 = new Car("c", "typeC", 2002, 300000, "c");
		Car c4 = new Car("d", "typeD", 2003, 400000, "d");
		Car c5 = new Car("e", "typeE", 2004, 500000, "e");
		
		// 1. 배열의 현재크기를 알아볼때는 size()를 이용하면 된다.
	      System.out.println("carList.size(): "+carList.size());
	      System.out.println("객체는 만들고 add 하기전");
	      System.out.println();
	    //2. 어레이리스트에 새로운 객체를 추가할 때에는 add()르 이용하면 된다.
	      carList.add(c1);
	      System.out.println("carList.size(): "+carList.size());
	      carList.add(c2);
	      System.out.println("carList.size(): "+carList.size());
	      carList.add(c3);
	      System.out.println("carList.size(): "+carList.size());
	      carList.add(c4);
	      System.out.println("carList.size(): "+carList.size());
	      carList.add(c5);
	      System.out.println("carList.size(): "+carList.size());
	      System.out.println();

	      //3. 어레이 리스트에서 해당 위치에 있는 객체를 호출할 떄엔 get()메소드를 사용하면 된다.
	      System.out.println("carList.get(1): "+carList.get(1));
	      //get으로 호출한 객체는 '배열의 몇번째 칸에 있는 객체다'처럼 우리가 그 객체의 메소드를 실행해 줄 수 있다.
	      System.out.println("carList.get(0).getType(): "+carList.get(0).getType());
	      
	      //4. 어레이 리스트에서 객체를 제거할 때에는 2가지 방법이 가능하다.
	      //A) 인덱스로 삭제하기
	      //	인덱스로 삭제할 때에는 remove(inmdex)를 하면 된다.
	      System.out.println("carList.get(0): "+carList.get(0));
	      carList.remove(0);
	      System.out.println("carList.get(0): "+carList.get(0));
	      	
	      //B) 객체로 삭제하기
	      //	객체로 삭제할 때에는 해당 객체와 equals()가 true가 나오는 객체를 넣어주면된다.
	      Car c44 = new Car("d","typeD",2003,400000,"d");
	      Car c55 = new Car("e","typeE",2004,500000,"e");
		
	      System.out.println("c4.equals(c44): "+c4.equals(c44));
	      System.out.println("carList.size(): "+carList.size());
	      carList.remove(c44);
	      System.out.println("car.List.size(): "+carList.size());
	      carList.remove(c55);
	      System.out.println("car.List.size(): "+carList.size());
	      
	}
}

 

이렇게 결과가 나온다.

728x90

'JAVA' 카테고리의 다른 글

배열 연습문제 05  (0) 2020.09.24
상속  (0) 2020.09.24
set, get 메소드를 사용하는 이유  (0) 2020.09.17
[메소드]toString()메소드  (0) 2020.09.16
배열 연습문제04  (0) 2020.09.12

+ Recent posts