자바 정의 제 한 된 형식 매개 변수 작업
제 한 된 매개 변수 형식의 방법 예시
경계 형식 매개 변 수 를 설명 하려 면 형식 매개 변수의 이름,뒷 굽 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:
Class A { /* … / } interface B { / … / } interface C { / … */ }
class D
class D
범용 알고리즘
경계 유형 매개 변 수 는 범 형 알고리즘 을 실현 하 는 관건 이다.다음 방법 을 고려 하여 이 방법 은 배열 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;
}
이상 의 자바 정의 가 제 한 된 유형 매개 변수 조작 은 바로 작은 편집 이 여러분 에 게 공유 하 는 모든 내용 입 니 다.여러분 께 참고 가 되 고 저희 도 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.