我在书中遇到了基本概念的问题。我应该创建一个方法swap();使用泛型交换第一和第二位置。我相信我的方法是正确的,但是我将配对类中的代码从T,S更改为T,因为我遇到了错误,并认为这样可以解决问题,但事实并非如此。我的问题是我现在在我的演示类中遇到了很多编译时错误,我找不到解决方案。
public class Pair<T>
{
private T first;
private T second;
public Pair(T firstElement, T secondElement)
{
first = firstElement;
second = secondElement;
}
public T getFirst() { return first; }
public T getSecond() { return second; }
public void swap()
{
T temp = first;
first = second;
second = temp;
}
public String toString() { return "(" + first + ", " + second + ")"; }
}
这是我得到的编译时错误。
PairDemo.java:23: error: wrong number of type arguments; required 1
public static Pair<String, Integer> firstContaining(
^
PairDemo.java:6: error: wrong number of type arguments; required 1
Pair<String, Integer> result = firstContaining(names, "a");
^
PairDemo.java:11: error: cannot find symbol
swap();
^
symbol: method swap()
location: class PairDemo
PairDemo.java:30: error: wrong number of type arguments; required 1
return new Pair<String, Integer>(strings[i], i);
^
PairDemo.java:33: error: wrong number of type arguments; required 1
return new Pair<String, Integer>(null, -1);
这是我的演示类
public class PairDemo
{
public static void main(String[] args)
{
String[] names = { "Tom", "Diana", "Harry" };
Pair<String, Integer> result = firstContaining(names, "a");
System.out.println(result.getFirst());
System.out.println("Expected: Diana");
System.out.println(result.getSecond());
System.out.println("Expected: 1");
swap();
}
public static Pair<String, Integer> firstContaining(
String[] strings, String sub)
{
for (int i = 0; i < strings.length; i++)
{
if (strings[i].contains(sub))
{
return new Pair<String, Integer>(strings[i], i);
}
}
return new Pair<String, Integer>(null, -1);
}
}
答案 0 :(得分:4)
如果您希望Pair的元素具有不同的类型,则必须使Pair类具有两个通用参数:Pair&lt; T,U&gt;然后使第二个字段为U. Swap然后显然返回一对&lt; U,T&gt;并且无法置换此引用。
就像
public Pair<U,T> swap() {
return new Pair(second, first);
}