JAVA 泛型

泛型的意义:编写的代码可以被很多不同类型的对象用,不必为不同的对象分别编写不同的类。

 

public class GenericMethodTest
{
   // 泛型方法 printArray                         
   public static < E > void printArray( E[] inputArray )
   {
      // 输出数组元素            
         for ( E element : inputArray ){        
            System.out.printf( "%s ", element );
         }
         System.out.println();
    }
 
    public static void main( String args[] )
    {
        // 创建不同类型数组: Integer, Double 和 Character
        Integer[] intArray = { 1, 2, 3, 4, 5 };
        Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
        Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };
 
        System.out.println( "整型数组元素为:" );
        printArray( intArray  ); // 传递一个整型数组
 
        System.out.println( "\n双精度型数组元素为:" );
        printArray( doubleArray ); // 传递一个双精度型数组
 
        System.out.println( "\n字符型数组元素为:" );
        printArray( charArray ); // 传递一个字符型数组
    } 
}

假定我们有这样一个需求:写一个排序方法,能够对整型数组、字符串数组甚至其他任何类型的数组进行排序,该如何实现?

答案是可以使用 Java 泛型

使用 Java 泛型的概念,我们可以写一个泛型方法来对一个对象数组排序。然后,调用该泛型方法来对整型数组、浮点数数组、字符串数组等进行排序。

 

泛形的定义:

public class Pair<T> 
{

//泛形变量的定义 private T mane ,public T name
   private T first;
   private T second;

//无参构造
   public Pair() { 
     first = null; 
     second = null;
   }

//有参构造
   public Pair(T first, T second) 
   { 
    this.first = first;  
    this.second = second; 
   }
//getter
   public T getFirst() 
   { 
     return first; 
   }

   public T getSecond() 
   { 
     return second; 
   }
//setter
   public void setFirst(T newValue) 
   { 
     first = newValue; 
   }

   public void setSecond(T newValue) 
   { 
     second = newValue; 
   }
}

多变量泛型类定义

public class pair<T,U>{....}

泛型实例化,用具体的类型代替字母T,通常用 T  U S 代表任意类型,

//泛形实列化

Pair<String>
Pair<Strdent>
Pair<Teacher>

例:

public class PairTest1 {
	
	
	public static void main(String[] args) {
		
		String[] words= {"Mary", "had", "a", "little", "lamb"};
		
		Pair<String> mm=ArrayAlg.minmax(words);
		
		System.out.println(mm.getFirst());
		
		System.out.println(mm.getSecond());
		
		
	}

}


class ArrayAlg{
   
//Pair<String> 为返回列类型
	
	public static Pair<String> minmax(String[] a)
	
	{
		
		
		
		if(a==null ||a.length==0) 
        { 
          return null;
        }

			
		String min=a[0];
			
		String max=a[0];
			
		for(int i=1;i<a.length;i++) 
		{
			
			if(min.compareTo(a[i])>0) {
					
					min=a[i];
					
				}
				
			if(max.compareTo(a[i])<0) {
					
					max=a[i];
					
				}

		}

		return new Pair<>(min,max);//返回的是泛形实列

	}

}

泛型方法的定义,普通类中也可以定义泛型主法

Class ArrayAlg{


  public static <T> T getMIddle(T... a)
  {
   
    return a[a.length/2];

  }



}


//调用泛型方法

String middle=ArrayAlg.<String>getMIddle("John","XX","hello");

类型变量的约束

有时,类或方法需要对类型变量加以约束

Class ArrayAlg
{

 public static <T> T min(T[] a)
 {
  
  if(a==null|| a.length==0){
   
     return null;

   }

   T smallest=a[0];
   
   for(int i=1; i<a.length;i++){
     
       if(ssmallest.compareTo(a[i])>0) {
       
        smallest=a[i];

       }
    return smallest;

   }
    

  }



}

以上变量 smallest 类型为T,这意味着,它可以是任何一个类型,怎么才能确信T所属的类有compareTo方法呢

解决这个问题的办法是,将T限制为实现了Comparable接口的类

public static <T extends comparable> T min(T[] a).........

 

public class Pair<T> 
{
   private T first;
   private T second;

   public Pair() { first = null; second = null; }
   public Pair(T first, T second) { this.first = first;  this.second = second; }

   public T getFirst() { return first; }
   public T getSecond() { return second; }

   public void setFirst(T newValue) { first = newValue; }
   public void setSecond(T newValue) { second = newValue; }
}
import java.time.*;

public class PairTest2
{
   public static void main(String[] args)
   {
      LocalDate[] birthdays = 
         { 
            LocalDate.of(1906, 12, 9), // G. Hopper
            LocalDate.of(1815, 12, 10), // A. Lovelace
            LocalDate.of(1903, 12, 3), // J. von Neumann
            LocalDate.of(1910, 6, 22), // K. Zuse
         };
      Pair<LocalDate> mm = ArrayAlg.minmax(birthdays);
      System.out.println("min = " + mm.getFirst());
      System.out.println("max = " + mm.getSecond());
   }
}

class ArrayAlg
{
   //如果是多限定,则是 <T extends Comparable & Serializable>
   public static <T extends Comparable> Pair<T> minmax(T[] a) 
   {
      if (a == null || a.length == 0) return null;
      T min = a[0];
      T max = a[0];
      for (int i = 1; i < a.length; i++)
      {
         if (min.compareTo(a[i]) > 0) min = a[i];
         if (max.compareTo(a[i]) < 0) max = a[i];
      }
      return new Pair<>(min, max);
   }
}

泛型类型的继承规则........

泛型类型 和反射...............

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值