return a Collection (Set or List)
The scanFile method returns a List. Sometimes, however, I want it to
return a Set. When I change the return type to Collection I get an error:
a00720398/data/BedAndBreakfast.java:33: incompatible types
found : java.util.Collection<a00720398.data.Guest>
required: java.util.List<a00720398.data.Guest>
guests = console.scanFile(new File("Guests.txt"), new GuestFactory
());
^
1 error
I've seen Collection used as a parameter in a signature, can it also be
used as a return type? A quick Google seems to show "yes". Is there a
better way of getting the most out of this method?
thufir@arrakis:~/bcit-comp2611-project1$
thufir@arrakis:~/bcit-comp2611-project1$ cat src/a00720398/ui/Console.java
/**
* Console.java
*/
package a00720398.ui;
import java.util.*;
import java.io.*;
import a00720398.data.*;
import a00720398.interfaces.*;
import a00720398.util.*;
public class Console {
public Console(){}
public <T> List<T> scanFile(File file, Factory<T> factory) {
List<String> lines = new ArrayList<String>();
List<T> list = new ArrayList<T>();
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
try {
T object = factory.make
(line);
list.add(object);
} catch (DataException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return list;
}
public void output(List<?> objects, File f){
try {
RandomAccessFile file = new RandomAccessFile(f,
"rw");
try {
file.seek(file.length
()); //go to end of file
file.writeUTF(objects.toString()); //
append the collection
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
thufir@arrakis:~/bcit-comp2611-project1$
thufir@arrakis:~/bcit-comp2611-project1$
thanks,
Thufir