【DataStructure】The description of generic collections

 In this blog, generic collections will be talked about  in details.  In the past bacause of shortage of generic argument,  less importance has been attached to the this module. Just now after reading the chapter about this knowledge, I gradually realized that they are so useful in the pactice, especially desgin the system achitect. Now make a summary about generic collections.

First, use the type argument 

package com.albertshao.ds.generic;

public class EnumArgument {

	enum Week {
		Mon, Tus, Wed, Thu, Fri, Sta, Sun
	}
	
	public static void main(String args[])
	{
		Pair<Integer, Week> pairs = new Pair<Integer, Week>(2, Week.Mon);
		System.out.println(pairs);
	}
}

class Pair<S, T> {
	private S first;
	private T second;

	public Pair(S first, T second)
	{
		this.first = first;
		this.second = second;
	}
	
	public S getFirst() {
		return first;
	}

	public void setFirst(S first) {
		this.first = first;
	}

	public T getSecond() {
		return second;
	}

	public void setSecond(T second) {
		this.second = second;
	}
	
	public String toString()
	{
		return "("+first + "," + second+")";
	}
}

/**
 * output:(2,Mon)
 */
Second, use the generic methods

   In addition to generic types, type parameters can also be used to define generic methods, identified by the generic parameter specifier<T> placed in front of the return type. 

package com.albertshao.ds.generic;

public class TestPrint {

	public static void main(String[] args) {
		String[] weeks = new String[] { "Mon", "Tus", "Wed" };
		print(weeks);
	}

	static <E> void print(E[] a) {
		for (E e : a) {
			System.out.println(e);
		}
	}
}

/*
 * output:
 * Mon
 * Tus
 * Wed
 * 
 */

Third , use generic wildcards

The symbol ?can be used as a wildcard, in place of a generic variable. It stands for “unknown type,” and is called the wildcard type.

package com.albertshao.ds.generic;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

public class TestWildCards {

	public static void main(String[] args) {
		List<String> strList = Arrays.asList("Fri", "Sat", "Sun");
		print(strList);
	}

	static void print(Collection<?> c) {
		for (Object o : c) {
			System.out.printf("%s ", o);
		}
		System.out.println();
	}
}

// output: Fri Sat Sun 







  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值