mercredi 11 mars 2015

Using generics to make a swap method


Vote count:

0




I'm having trouble with a basic concept in my book. I am supposed to make a method swap(); that swaps positions with first and second using generics. I believe my method is correct however I changed the code in the pair class from T,S to T because I was getting errors and thought that would solve the issue but this is not the case. My problem is that I now get a lot of compile time errors in my demo class and I cannot find a solution.



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 + ")"; }
}


This is the compile time error that I am getting.



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);


This is my demo class



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);
}
}


asked 23 secs ago







Using generics to make a swap method

Aucun commentaire:

Enregistrer un commentaire