Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / May 2008

Tip: Looking for answers? Try searching our database.

return a Collection (Set or List)

Thread view: 
thufir - 13 May 2008 12:29 GMT
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
Lew - 13 May 2008 13:18 GMT
> 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:
[quoted text clipped - 9 lines]
> 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".  

You really should show the part of the code that actually has the problem.  Read
 http://sscce.org/
to find out how.

The problem is not the return of the Collection but its assignment to a
narrower type.  You can assign a List<Foo> to a Collection<Foo> but not the
other way around.

If that's not what happened, but I'll bet it is, then you should have shown
the declaration of 'guests'.  Or, for that matter, 'console' and 'scanFile()'.

Signature

Lew

Roedy Green - 13 May 2008 13:40 GMT
>found   : java.util.Collection<a00720398.data.Guest>
>required: java.util.List<a00720398.data.Guest>
>        guests = console.scanFile(new File("Guests.txt"), new GuestFactory
>());
>                                 ^

All Lists are Collections but not all Collections are Lists.  Java
insists on an explicit cast when the conversion might conceivably
fail, e.g. Collection -> List.

You need to have your method return a List<Guest> or you need to cast
the assignment with:  

guests  = (List <Guest>)xxxx;
Signature


Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Mark Space - 13 May 2008 19:37 GMT
>> found   : java.util.Collection<a00720398.data.Guest>
>> required: java.util.List<a00720398.data.Guest>
[quoted text clipped - 10 lines]
>
> guests  = (List <Guest>)xxxx;

This works, but is a little hackish.  As you say, sometimes you will
return a Set.  The above will fail if you do return a set.

Consider substituting two methods for this one.  "getAsList" and
"getAsSet" Then the caller can indicate which type is desired and always
receive the correct type.

You can use built-in methods to transform Lists to Sets and vice versa.
 It's usually just a couple of method calls.  Actually you could do
this externally too and not have to touch your class.  Always get a
list.  If you need a set, just transform the List into a Set.

You could always just:

   List myList
   myList = getSomeList();
   Set mySet = new SomeSet();
   mySet.addAll( myList );

This feels a bit safer to me than casting something that might fail.
Roedy Green - 13 May 2008 20:39 GMT
On Tue, 13 May 2008 11:37:53 -0700, Mark Space
<markspace@sbc.global.net> wrote, quoted or indirectly quoted someone
who said :

>Consider substituting two methods for this one.  "getAsList" and
>"getAsSet" Then the caller can indicate which type is desired and always
>receive the correct type.

If it is always possible to get as List, why would you ever return
anything else?  You can always use a List as a Set.
Signature


Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Eric Sosman - 13 May 2008 21:13 GMT
> On Tue, 13 May 2008 11:37:53 -0700, Mark Space
> <markspace@sbc.global.net> wrote, quoted or indirectly quoted someone
[quoted text clipped - 6 lines]
> If it is always possible to get as List, why would you ever return
> anything else?  You can always use a List as a Set.

    String[] words = { "The", "thing", "about", "Sets",
       "is", "that", "each", "item", "is", "present",
       "once", "and", "once", "only." };
    List<String> list = new ArrayList<String>();
    Set<String> set = new HashSet<String>();
    for (String w : words) {
       list.add(w);
       set.add(w);
    }
    assert list.size() == words.length;
    assert set.size() == words.length;  // BZZZZT!

Signature

Eric.Sosman@sun.com

Lew - 14 May 2008 00:41 GMT
>> On Tue, 13 May 2008 11:37:53 -0700, Mark Space
>> <markspace@sbc.global.net> wrote, quoted or indirectly quoted someone
[quoted text clipped - 18 lines]
>     assert list.size() == words.length;
>     assert set.size() == words.length;  // BZZZZT!

Set <String> strangs = new ArrayList <String> (); // BZZZZT!

Signature

Lew

Roedy Green - 14 May 2008 09:22 GMT
>Set <String> strangs = new ArrayList <String> (); // BZZZZT!

Egg on beard.  A List is a Collection, but it is NOT a Set.
Signature


Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

thufir - 13 May 2008 23:38 GMT
> You could always just:
>
[quoted text clipped - 4 lines]
>
> This feels a bit safer to me than casting something that might fail.

I like this, thanks.

-Thufir
RedGrittyBrick - 14 May 2008 10:27 GMT
>> You could always just:
>>
[quoted text clipped - 6 lines]
>
> I like this, thanks.

I bet you'd all omit the intermediate variables. e.g.

     Set mySet = new HashSet(getSomeList());

Signature

RGB

Lew - 14 May 2008 13:07 GMT
Mark Space wrote:
>>> You could always just:
>>>
[quoted text clipped - 4 lines]
>>>
>>> This feels a bit safer to me than casting something that might fail.

> I bet you'd all omit the intermediate variables. e.g.
>
>      Set mySet = new HashSet(getSomeList());

If the statements are truly contiguous, of course.  Or you could take the
separated declarations and statements as a template for situations with
intervening lines of code between the illustrated statements.

Signature

Lew



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.