收录日期:2019/10/18 22:13:18 时间:2009-11-11 00:34:09 标签:java,collections

Assume a class (for instance URI) that is convertable to and from a String using the constructor and toString() method.

I have an ArrayList<URI> and I want to copy it to an ArrayList<String>, or the other way around.

Is there a utility function in the Java standard library that will do it? Something like:

java.util.collections.copy(urlArray,stringArray);

I know there are utility libraries that provide that function, but I don't want to add an unnecessary library.

I also know how to write such a function, but it's annoying to read code and find that someone has written functions that already exist in the standard library.

No, there is no standard JDK shortcut to do this.

I know you don't want to add additional libraries, but for anyone who finds this from a search engine, in google-collections you might use:

List<String> strings = Lists.transform(uris, Functions.toStringFunction());

one way, and

List<String> uris = Lists.transform(strings, new Function<String, URI>() {
  public URI apply(String from) {
     try {
       return new URI(from);
     } catch (URISyntaxException e) {
       // whatever you need to do here
     }
  }
});

the other.

Have a look at commons-collections:

http://commons.apache.org/collections/

I believe that CollectionUtils has a transform method.

Since two types of collections may not be compatible, there is no built-in method for converting one typed collection to another typed collection.

Try:

public ArrayList<String> convert(ArrayList<URI> source) {
    ArrayList<String> dest=new ArrayList<String>();

    for(URI uri : source)
        dest.add(source.toString());

   return dest;
}

Seriously, would a built-in API offer a lot to that?

Also, not very OO. the URI array should probably be wrapped in a class. The class might have a .asStrings() method.

Furthermore you'll probably find that you don't even need (or even want) the String collection version if you write your URI class correctly. You may just want a getAsString(int index) method, or a getStringIterator() method on your URI class, then you can pass your URI class in to whatever method you were going to pass your string collection to.