Java面向对象 集合(中)



Java面向对象 集合(中)


知识概要:

                  (1)泛型的体系概念

                  (2)泛型的特点

                  (3)自定义泛型类


泛型的体系概念

          泛型:JDK1.5版本以后出现新特性。用于解决安全问题,是一个类型安全机制。


 泛型出现的原因 

       我们在编写程序时,经常遇到两个模块的功能非常相似,只是一个是处理int数据,另一个是处理string数据,或 者其他自定义的数据类型,但我们没有办法,只能分别写多个方法处理每个数据类型,因为方法的参数类型不同。有没有一种办法,在方法中传入通用的数据类型,这样不就可以合并代码了吗?泛型的出现就是专门解决这个问题的。读完本篇文章,你会对泛型有更深的了解。

好处
      
1.将运行时期出现问题ClassCastException,转移到了编译时期,方便于程序员解决问题。让运行时问题减少,

       安全。

     2,避免了强制转换麻烦。


泛型格式:通过<>来定义要操作的引用数据类型。


在使用java提供的对象时,什么时候写泛型呢?

    通常在集合框架中很常见,只要见到<>就要定义泛型。其实<> 就是用来接收类型的。

    当使用集合时,将集合中要存储的数据类型作为参数传递到<>中即可。

class GenericDemo 
{
	public static void main(String[] args) 
	{

		ArrayList<String> al = new ArrayList<String>();

		al.add("abc01");
		al.add("abc0991");
		al.add("abc014");

		//al.add(4);//al.add(new Integer(4));
		

		Iterator<String> it = al.iterator();
		while(it.hasNext())
		{
			String s = it.next();

			System.out.println(s+":"+s.length());
		}
	}
}

自定义泛型类

   泛型类定义的泛型,在整个类中有效。

   如果被方法使用,那么泛型类的对象明确要操作的具体类型后,所有要操作的类型就已经固定了。
   
   为了让不同方法可以操作不同类型,而且类型还不确定。

   那么可以将泛型定义在方法上。



  特殊之处:
  静态方法不可以访问类上定义的泛型。    

  如果静态方法操作的应用数据类型不确定,可以将泛型定义在方法上。


 

class Demo<T>
{
	public  void show(T t)
	{
		System.out.println("show:"+t);
	}
	public <Q> void print(Q q)
	{
		System.out.println("print:"+q);
	}
	public  static <W> void method(W t)
	{
		System.out.println("method:"+t);
	}
}
class GenericDemo4 
{
	public static void main(String[] args) 
	{
		Demo <String> d = new Demo<String>();
		d.show("haha");
		//d.show(4);
		d.print(5);
		d.print("hehe");

		Demo.method("hahahahha");

		/*
		Demo d = new Demo();
		d.show("haha");
		d.show(new Integer(4));
		d.print("heihei");
		*/
		/*
		Demo<Integer> d = new Demo<Integer>();

		d.show(new Integer(4));
		d.print("hah");

		Demo<String> d1 = new Demo<String>();
		d1.print("haha");
		d1.show(5);
		*/
	}
}

泛型定义在接口上。
     
interface Inter<T>
     
{
       void show(T t);
     
}

   ? 通配符。也可以理解为占位符。
    泛型的限定;
   ? extends E: 可以接收E类型或者E的子类型。上限。
       ? super E: 可以接收E类型或者E的父类型。下限

class  GenericDemo6
{
	public static void main(String[] args) 
	{
		

		ArrayList<Person> al = new ArrayList<Person>();
		al.add(new Person("abc1"));
		al.add(new Person("abc2"));
		al.add(new Person("abc3"));
		printColl(al);

		ArrayList<Student> al1 = new ArrayList<Student>();
		al1.add(new Student("abc--1"));
		al1.add(new Student("abc--2"));
		al1.add(new Student("abc--3"));
		printColl(al1);  

	}
	public static void printColl(Collection<? extends Person> al)
	{
		Iterator<? extends Person> it = al.iterator();


		while(it.hasNext())
		{
			System.out.println(it.next().getName());
		}
	}

}

class Person
{
	private String name;
	Person(String name)
	{
		this.name = name;
	}
	public String getName()
	{
		return name;
	}
}

class Student extends Person
{
	Student(String name)
	{
		super(name);
	}

}



posted @ 2014-05-30 19:17  博客园杀手  阅读(320)  评论(0编辑  收藏  举报