ArrayList
특징 : Object[ ] 배열의 데이터구조를 갖고 있다.
배열의 길이에 제약이 없다.
1. 실행클래스를 만든다.
import java.util.ArrayList;
import kr.bit.Book;
public class TPC37 {
public static void main(String[] args) {
ArrayList list = new ArrayList(); //Object[] 배열을 가지고 있음
list.add(new Book("자바", 12000,"이지스", 600)); //add동작 : upcasting (Book타입-->Object타입)
list.add(new Book("C언어", 17000,"에이콘", 700));
list.add(new Book("Python", 15000,"이지스", 610));
for(int i=0; i<list.size(); i++) {
Object obj = list.get(i); //downcasting(Object타입--->Book타입)
Book b=(Book)obj;
System.out.println(b.title+"\t"+b.price+"\t"+
b.company+"\t"+b.page);
}
}
}
2. ArrayList에 담을 객체(클래스)를 만든다.
package kr.bit;
//책(객체) -> 제목, 가격, 출판사, 페이지수 ..(상태정보:필드)+(행위정보:메서드)
public class Book {
public String title;
public int price;
public String company;
public int page;
public Book(){};
public Book(String title, int price, String company, int page) {
this.title =title;
this.price = price;
this.company = company;
this.page = page;
}
}
'자바 > Java TPC(생각하고, 표현하고, 코딩하고)' 카테고리의 다른 글
Wrapper클래스 (0) | 2022.10.27 |
---|---|
내가 만든 최초의 API - IntArray, ObjectArray (0) | 2022.10.27 |
문자열(String)이 객체라고요? (0) | 2022.10.27 |
Object 클래스는 신이야 (0) | 2022.10.27 |
추상클래스 vs 인터페이스 (0) | 2022.10.27 |