Java에서 람다 표현식을 배우고 있지만 일반 유형과 함께 사용하려고 생각했습니다. (예 : int, String). Java에서 람다 표현식을 사용하는 방법을 배우고 연구하는 한 인터페이스에서 선언해야합니다. 그런 다음 사용하려는 구현을 정의하십시오. (예 (prototype args) -> {definition}
). 아래에서 볼 수 있듯이 유형 문제에 대한 기본 예제를 작성하려고 시도했습니다. 나는 단지 그것을 운동 으로 String
, int
유형과 함께 사용하려고 생각했습니다 . 그러나 제네릭 유형을 0
. 을 위해 할 수 있습니다 null
. 그런 식으로 null
동일한 지 확실하지 않습니다 0
. 문제를 어떻게 해결할 수 있습니까?
public class Test<T,U> {
public static <T,U> void main(String[] args) {
Test myTest = new Test();
Str myHello = (message1, message2) -> {
System.out.println("Hello " + message1 + message2);};
myHello.welcome("Mr. ", "rickroll");
MyGen addition = (U... operationArgs) -> {
T sum = 0;
for (U i : operationArgs) {
sum += i;
}
return sum;};
System.out.println("2+3+4+5 = " + myTest.operate(addition, 2, 3, 4, 5));
System.out.println("A.....gl ?" + myTest.operate(addition, "b", "c", "d", "e", "f"));
}
private T operate(MyGen choice, U... args) {
return (T)choice.asYouWish(args);
}
interface Str {
public void welcome(String a, String b);
}
interface MyGen<T,U> {
public T asYouWish(U... args);
}
}
여러 유형 매개 변수를 사용하지 않고 선언하고 있으며 이름이 같음에도 불구하고 이들이 독립적 인 유형 매개 변수라는 사실을 이해하지 못할 수도 있습니다. 유형 매개 변수로 클래스를 선언 할 때 해당 클래스를 사용할 때 유형 인수를 선언해야합니다.
따라서 다음과 같은 클래스를 정의 할 때
public class Test<T,U> {
public static <T,U> void main(String[] args) { … }
private T operate(MyGen choice, U... args) { … }
interface MyGen<T,U> {
public T asYouWish(U... args);
}
}
선언하는 것과 다르지 않습니다
public class Test<T,U> {
public static <A,B> void main(String[] args) { … }
private T operate(MyGen choice, U... args) { … }
interface MyGen<X,Y> {
public X asYouWish(Y... args);
}
}
그들 모두를 이름으로 T
하고 U
관계를 만들지 않습니다 만 인간의 독자를 혼동한다. 클래스의 유형 매개 변수는 비 static
멤버에만 영향을 미치며 의 유일한 비 static
멤버는 실제 유형 인수없이 참조 Test
하는 method 입니다.operate
MyGen
올바른 사용법은
private T operate(MyGen<T,U> choice, U... args) {
return choice.asYouWish(args);
}
따라서의 MyGen
매개 변수화에 따라 매개 변수가 매개 변수화되어야 한다고 선언하고 있습니다. Test
이제 asYouWish
경고없이 유형 캐스트없이 호출 할 수 있습니다 .
에 대한 유형 인수를 정의 할 때 및 인스턴스화 할 때 s 및 s에 Test
대한 메서드를 사용하기 위해의 동일한 인스턴스를 사용할 수 없다는 점을 강조해야합니다 .String
Integer
T
U
Test
또한 main
메서드 의 형식 매개 변수는 Test
의 형식 매개 변수와 독립적이며 메서드의 서명에 사용되지 않기 때문에 매우 쓸모가 없습니다. 람다 식 내에서 참조하는 것은 무의미합니다. 람다 식의 본문에 컴파일러 오류가 없더라도 함수를 사용할 범위에 해당 유형의 인스턴스가 없습니다.
합치면
public class Test<T,U> {
public static void main(String[] args) {
Str myHello = (message1, message2) ->
System.out.println("Hello " + message1 + message2);
myHello.welcome("Mr. ", "rickroll");
{
Test<Integer,Integer> myTest = new Test();
MyGen<Integer,Integer> addition = operationArgs -> {
int sum = 0;
for(int i: operationArgs) sum += i;
return sum;
};
System.out.println("2+3+4+5 = " + myTest.operate(addition, 2, 3, 4, 5));
}
{
Test<String,String> myTest = new Test();
MyGen<String,String> addition = operationArgs -> {
String sum = "";
for(String i: operationArgs) sum += i;
return sum;
};
System.out.println("A.....gl ?"
+ myTest.operate(addition, "b", "c", "d", "e", "f"));
}
}
private T operate(MyGen<T,U> choice, U... args) {
return choice.asYouWish(args);
}
interface Str {
public void welcome(String a, String b);
}
interface MyGen<X,Y> {
public X asYouWish(Y... args);
}
}
어쨌든 인스턴스가 필요하지 않기 때문에 Test
단순히을 operate
제네릭 static
메서드로 전환하여 인스턴스 를 매개 변수화하는 요구 사항을 제거 할 수 있습니다 . 일반 MyGen
함수 를 정의 하려면 +
연산자 를 추상화해야 합니다. String
케이스 의 모양과 달리 Java에서는 연산자 오버로딩이 없습니다.
또한 0
문자열에 동일한 함수를 사용하려고 할 때 마술처럼 빈 문자열로 바뀌지 않기 때문에 중립 요소없이 구현해야합니다 .
import java.util.function.BinaryOperator;
public class Test {
public static void main(String[] args) {
Str myHello = (message1, message2) ->
System.out.println("Hello " + message1 + message2);
myHello.welcome("Mr. ", "rickroll");
example(Integer::sum, "2+3+4+5 = ", 2, 3, 4, 5);
example(String::concat, "A.....gl ?", "b", "c", "d", "e", "f");
}
private static <E> void example(BinaryOperator<E> plus, String head, E... values) {
MyGen<E,E> addition = args -> {
E sum=args[0];
for(int ix=1; ix<args.length; ix++) sum = plus.apply(sum, args[ix]);
return sum;
};
System.out.println(head + Test.operate(addition, values));
}
private static <T,U> T operate(MyGen<T,U> choice, U... args) {
return choice.asYouWish(args);
}
interface Str {
public void welcome(String a, String b);
}
interface MyGen<X,Y> {
public X asYouWish(Y... args);
}
}
이 작업은 이미 수행되었으므로 데모 목적으로 만 사용됩니다. 예를 들어 example
방법을 다음과 같이 변경할 수 있습니다 .
private static <E> void example(BinaryOperator<E> plus, String head, E... values) {
MyGen<E,E> addition = args -> Arrays.stream(args).reduce(plus).get();
System.out.println(head + Test.operate(addition, values));
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다