문제풀이

객체배열과 ArrayList

  • Dog 클래스를 참고하여 DogTest 클래스와 배열 길이가 5인 Dog[] 배열을 만든 후,
  • Dog 인스턴스를 5개 생성하여 배열에 추가한다.
  • for문과 향상된 for문을 이용하여 출력한다.

 

  • Dog 클래스
class Dog {
	private String name;
	private String type;
	
	Dog(String name, String type){
		this.name = name;
		this.type = type;
	}
	
	String getName() {
		return name;
	}
	void setName(String name) {
		this.name = name;
	}
	String getType() {
		return type;
	}
	void setType(String type) {
		this.type = type;
	}
	
	String showDogInfo() {
		return name +", "+ type;
	}
}

 

 

  • 객체 배열
public class Array06DogTest {
	public static void main(String[] args) {

		Dog[] dogArray = new Dog[5];
		
		dogArray[0] = new Dog("호두", "말티즈");
		dogArray[1] = new Dog("솜이", "진돗개");
		dogArray[2] = new Dog("재롱이", "삽살개");
		dogArray[3] = new Dog("찹쌀", "샤모에드");
		dogArray[4] = new Dog("탄이", "시바견");
		
		for(int i =0; i<dogArray.length; i++) {
			System.out.println(dogArray[i].showDogInfo());
		}
		for(Dog d : dogArray) {
			System.out.println(d.showDogInfo());
		}
	}
}

 

 

  • ArrayList
public class Array06DogTest {
	public static void main(String[] args) {
    
		ArrayList<Dog> dog = new ArrayList<Dog>();
		
		dog.add(new Dog("호두", "말티즈"));
		dog.add(new Dog("솜이", "진돗개"));
		dog.add(new Dog("재롱이", "삽살개"));
		dog.add(new Dog("찹쌀", "샤모에드"));
		dog.add(new Dog("탄이", "시바견"));
		
		for(int i=0; i<dog.size(); i++) {
			Dog d2 = dog.get(i);
			System.out.println( d2.showDogInfo() );
		}
	}
}
728x90
728x90

'문제풀이' 카테고리의 다른 글

이름에 해당하는 id 맞추기 게임  (0) 2022.06.08
ArrayList에 랜덤 숫자 저장하기, Map에서 검색하기  (1) 2022.06.06
Review 0606  (0) 2022.06.06
Review 0527  (0) 2022.05.30
백준 10818 - 1차원 배열  (0) 2022.05.17