본문 바로가기

언어/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' 카테고리의 다른 글