|
Prev: How should a container class "know" its contained objects?
Next: china wholesale nike jordan sneakers WWW.21cn-shoes.COM discount gucci prada puma
From: Daniel T. on 16 Jan 2008 23:32 chris_a_brooks(a)hotmail.co.uk wrote: > You've just used the fact Smalltalk provides this kind of language > construct to help you. I don't know too much about Java generics so I might be missing something, but here are the beginnings of the refactoring that is something like the SmallTalk example. interface Pred { boolean isTrue( Object o ); } public class Selector { public static Collection select( Collection c, Pred pred ) throws Exception { Collection result = collection.getClass().newInstance(); Iterator it = collection.iterator(); while ( it.hasNext() ) { Object each = it.next(); if ( pred.isTrue( each ) ) { result.add( each ); } } return result; } } It would be used like this: Collection matches = new Selector().select( allStrings, new Pred(){ public boolean isTrue( Object o ){ return ((String)o).startsWith(matchMe);}}); Granted, Java anonymous classes are a bit ungainly...
From: Bizonho on 27 Jan 2008 15:41 What do you think about extending the collection class you're using and adding a method that returns all elements of the collection that matches an implemented comparison? Like: public class Foo<T> extends ArrayList<T> { public ArrayList<T> getMatching(Comparator regex) { ... } } Sorry about the lazyness.. but did you get the proposal? Do you think it's a valid solution? Cheers
From: topmind on 27 Jan 2008 16:31
Personally, I'd prefer to use the RDBMS if possible to avoid transferring globs of data to the app side, but if I have to loop in code, KISS would dictate something like this: while (str = getnext()) { found = false; if (matchType=="startsWith") found=str.startsWith(compr); if (matchType=="endsWith") found=str.endsWith(compr); if (matchType=="contains") found=str.contains(compr); etc... if (found) { // process match } } (There's some minor efficiency adjustments not shown here.) Why are you guys making all these complicated OO contraptions? Maybe if and when we use this code over again for slightly different purposes, then different approaches can be looked at. But such has not been identified. You're gold-plating a shack. -T- |