본문 바로가기

언어/Java

향상된 for문

※ 배열이나 자료구조에서 사용 가능하다.

public class ProductDAOList implements ProductDAOInterface {
    private List<Product> products;
         @Override
	    public void insert(Product product) throws AddException {
            for(int i = 0; i<products.size(); i++) {
               Product p = products.get(i);
               if(p.equals(product)) {
				    throw new AddException("이미 존재하는 상품입니다");
			}
		}
		products.add(product);
	}
    
   // 위 for문을 아래처럼 향상된 for문으로 사용 가능하다.  
     @Override
	    public void insert(Product product) throws AddException {
		    for(Product p : products) {
                if(p.equals(product)) {
				    throw new AddException("이미 존재하는 상품입니다");
			}
		}
		products.add(product);
	}

 

'언어 > Java' 카테고리의 다른 글

Product 예제 2  (0) 2023.08.04
제네릭(element generic), ArrayList, HashSet 예시  (0) 2023.08.04
컬렉션 프레임워크(Java Collection Framework)  (0) 2023.08.04
어노테이션(Annotation)  (0) 2023.08.04
상속 예제문제  (0) 2023.08.04