gpt4 book ai didi

java 将 toString() 传递给方法

转载 作者:行者123 更新时间:2023-12-02 07:03:26 24 4
gpt4 key购买 nike

我有以下代码

public class Mamman14 {


public static void main(String[] args) {
// TODO code application logic here
}

public class SortedPair < E extends Comparable < E >> {
E Max_Element;
E Min_Element;

public SortedPair(E FirstElement, E SecondElemnt) throws IllegalPair {
int Compare_Result = FirstElement.compareTo(SecondElemnt);

if (Compare_Result == 0) {
Max_Element = null;
Min_Element = null;
throw new IllegalPair(FirstElement.toString(), SecondElemnt.toString());
} else if (Compare_Result > 0) {
Max_Element = FirstElement;
Min_Element = SecondElemnt;
} else {
Max_Element = SecondElemnt;
Min_Element = FirstElement;

}
}

public E getFirst() {
return Max_Element;
}

public E getSecond() {
return Min_Element;
}

@
Override
public String toString() {
return String.format("%s is bigger then %s.", getFirst(), getSecond());
}

}

public class IllegalPair extends Exception {
public IllegalPair() {
super("Elements must be different!!");
}

public IllegalPair(String Element) {
super("Elements must be different!! \n However they are equal to " + Element);
}

public IllegalPair(String Element1, String Element2) {
super("Elements must be different!! \n However the elements are " + Element1 + "and" +
Element2 + "and they are equal.");
}

}
}

这是一个简单的程序,它比较 2 个元素并相应地在 Max_Element 和 Min_Element 中设置它们。我有两个问题:

当我写public class SortedPair <E extends Comparable<E>>时这是否意味着 SortedPair 只能接收包含compareTo 方法的可比较元素?

在线 throw new IllegalPair(FirstElement.toString(), SecondElemnt.toString())我使用元素的 toString() 方法创建一个新对象,假设元素没有 toString() 方法,正在发送什么?

谢谢。

最佳答案

When I write public class SortedPair <E extends Comparable<E>> does that mean that SortedPair can receive only comparable elements which contains the compareTo method?

这意味着你只能使用实现 Comparable 的东西作为类型参数,例如:

SortedPair<String> sp;
// ^--- this must be a class that implements `Comparable`
// or an interface that extends `Comparable`

...这又意味着您可以使用 Comparable 定义的方法在使用泛型类型声明的任何实例上 E .

In the line throw new IllegalPair(FirstElement.toString(), SecondElemnt.toString()) I create a new object using the toString() method of the elements, lets say the elements don't have a toString() method, what is being send?

这将使用 toString from Object ,这很无聊。 :-) 这就是文档所说的:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

关于java 将 toString() 传递给方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16372321/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com