Java Generic WildCard PECS: producer-extends, consumer-super.

Categories: Java June 21st, 2014 13:49

Effective Java – Item 28: Use bounded wildcards to increase API flexibility

* PECS stands for producer-extends, consumer-super

*  Do not use wildcard types as return
types. Rather than providing additional flexibility for your users, it would  force them to use wildcard types in client code.

.

	@Test
	/**
	 * PECS stands for producer-extends, consumer-super.
	 */
	public void testAccountListUtils() {
		
		List corporationAccounts = new ArrayList();
		corporationAccounts.add(new CorporationAccount(1, "Google"));
		corporationAccounts.add(new CorporationAccount(2, "Yahoo"));
		
		List allAccounts = new ArrayList<>();
		
		AccountListUtils.mergeUserList(corporationAccounts, allAccounts);
		assertEquals(corporationAccounts.size(), allAccounts.size());
	}
package com.liguoliang.lang.collection;

import java.util.List;

import com.jpm.model.IAccount;

public class AccountListUtils < T extends IAccount >{
	
	public static  void mergeUserList(List tobeMerged, List allAccounts) {
		allAccounts.addAll(tobeMerged);
	}
}

more code

	@Test
	public void wildCard() {
		List corporationAccounts = new ArrayList<>();
		corporationAccounts.add(new CorporationAccount(1, "GE"));
		corporationAccounts.add(new CorporationAccount(2, "IBM"));
		
		IAccount account = getUserById(corporationAccounts, 2);
		System.out.println(account.getAccountName());
	}
	
	/**
	 * List and List are treated as two different types.
	 * If we use List as the parameter type, and call the method by getUserId(List, 
	 * will got this compile Error:
	 * 		The method getUserById_iAccount(List, int) in the type LearnGeneric 
	 * 		is not applicable for the arguments (List, int);
	 * @param accountList
	 * @param id
	 * @return
	 */
	public IAccount getUserById(List< ? extends IAccount> accountList, int id) {
		for (IAccount iAccount : accountList) {
			if(iAccount.getAccountId().equals(id)) {
				return iAccount;
			}
		}
		return null;
	}
	
	/**
	 * Note: getUserById(List and getaUserById(List) are not reloading methods:
	 * 		Erasure of method getUserById(List, int) is the same as another method in type LearnGeneric
	 * @param accountList
	 * @param id
	 * @return
	 */
	public IAccount getUserById_withoutWildCard(List accountList, int id) {
		for (IAccount iAccount : accountList) {
			if(iAccount.getAccountId().equals(id)) {
				return iAccount;
			}
		}
		return null;
	}

<->



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.