자바 정의 제 한 된 형식 매개 변수 작업

매개 변수 화 형식 에서 형식 매개 변수 로 사용 할 수 있 는 유형 을 제한 하고 싶 을 수도 있 습 니 다.예 를 들 어 숫자 를 조작 하 는 방법 은 Number 나 하위 클래스 의 인 스 턴 스 만 받 아들 이 기 를 바 랄 수 있 습 니 다.이것 이 바로 경계 유형의 매개 변수의 용도 다.
제 한 된 매개 변수 형식의 방법 예시
경계 형식 매개 변 수 를 설명 하려 면 형식 매개 변수의 이름,뒷 굽 extends 키 워드 를 보 여 주 십시오.그 다음 상한 선 입 니 다.이 예 에서 Number 입 니 다.
이러한 상황 에서 extends 는 보통'확장'(예 를 들 어 클래스 에서)또는'실현'(예 를 들 어 인터페이스 에서)을 나타 내 는 데 사 용 됩 니 다.

package generics;

/**
 *         
 * 
 * @author psdxdgK1DT
 *
 */
public class Box<T> {

	private T t;

	public void set(T t) {
		this.t = t;
	}

	public T get() {
		return t;
	}
/**
	 *                        ,       ,     inspect      String:
	 * By modifying our generic method to include this bounded type parameter
	 * compilation will now fail, since our invocation of inspect still includes a String:
	 * inspect:  :  
	 * @param <U>
	 * @param u
	 */
	public <U extends Number> void inspect(U u) {
		System.out.println("T:" + t.getClass().getName());
		System.out.println("U:" + u.getClass().getName());
	}

	public static void main(String[] args) {
		Box<Integer> integerBox = new Box<Integer>();
		integerBox.set(new Integer("some text"));
		integerBox.inspect("some test");          

		integerBox.inspect(10);
	}
}

모니터 에 빨간색 파도 선 이 컴 파일 오 류 를 표시 합 니 다.

컴 파일 을 강행 하면 오류 가 발생 합 니 다.
program run result:
Exception in thread “main” java.lang.Error: Unresolved compilation problem: The method inspect(U) in the type Box is not applicable for the arguments (String)
at generics.Box.main(Box.java:36)
번역문:
해결 되 지 않 은 컴 파일 오류
Box 클래스 의 inspect(U)방법 은(String)형식 인자 에 사용 할 수 없습니다\\
제 한 된 유형의 참 류 를 사용 하면 제 한 된 경계 방법 을 호출 할 수 있 습 니 다.
일반적인 형식 을 예화 할 수 있 는 유형 을 제한 하 는 것 외 에 경계 유형 매개 변 수 는 경계 에서 정의 하 는 방법 도 사용 할 수 있 습 니 다.

//          
public class NaturalNumber<T extends Integer> {

  private T n;
  public NaturalNumber(T n) { this.n = n; }

  public boolean isEven() {
    return n.intValue() % 2 == 0;
  }

  // ...
}
isEven 방법 은 n 을 통 해 Integer 클래스 에서 정의 하 는 intValue 방법 을 호출 합 니 다.
다 중 제한 경계(다 중 경계)
The preceding example illustrates the use of a type parameter with a single bound, but a type parameter can have multiple bounds:
A type variable with multiple bounds is a subtype of all the types listed in the bound. If one of the bounds is a class, it must be specified first. For example:
Class A { /* … / } interface B { / … / } interface C { / … */ }
class D { /* … */ } If bound A is not specified first, you get a compile-time error:
class D { /* … */ } // compile-time error
범용 알고리즘
경계 유형 매개 변 수 는 범 형 알고리즘 을 실현 하 는 관건 이다.다음 방법 을 고려 하여 이 방법 은 배열 T[]에서 지정 한 요소 elem 보다 큰 요소 수 를 계산 합 니 다.

public static <T> int countGreaterThan(T[] anArray, T elem) {
  int count = 0;
  for (T e : anArray)
    if (e > elem) // compiler error
      ++count;
  return count;
}
The implementation of the method is straightforward,
but it does not compile because the greater than operator (>) applies only to primitive types
such as short, int, double, long, float, byte, and char. 
You cannot use the > operator to compare objects. To fix the problem, use a type parameter
bounded by the Comparable<T> interface:

public interface Comparable<T> {
  public int compareTo(T o);
}
The resulting code will be:

public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) {
  int count = 0;
  for (T e : anArray)
  //     T         ,   Comparable  ,           compareTo
    if (e.compareTo(elem) > 0)
      ++count;
  return count;
}
이상 의 자바 정의 가 제 한 된 유형 매개 변수 조작 은 바로 작은 편집 이 여러분 에 게 공유 하 는 모든 내용 입 니 다.여러분 께 참고 가 되 고 저희 도 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기