The Source for Java Technology Collaboration
User: Password:



Start New Message Delete Post a Reply

Article: 
 (Not So) Stupid Questions 7: >>, >>>, <<, and ?: operators
Subject:  [Reposted] Otherwise known as a ternary operator
Date:  2006-01-17 13:56:54
From:  phuego
Response to: Otherwise known as a ternary operator


So sorry, completely forgot about formatting.

Here is the 'before' code from my first post.

    public List filterListOfIntegersToPositives(List original, boolean inclZero) { 
        List ret = new ArrayList(original.size()); 
        if (inclZero) { 
            // code that does filtering 
            for(int i=0; i<original.size(); i++){ 
                Integer thisInt = (Integer) original.get(i); 
                if (thisInt.compareTo(Integer.valueOf("0")) > -1) { 
                    ret.add(thisInt); 
                } 
            } 
            // end code that does filtering 
        } else { 
            // code that does filtering 
            for(int i=0; i<original.size(); i++){ 
                Integer thisInt = (Integer) original.get(i); 
                if (thisInt.compareTo(Integer.valueOf("0")) > 0) { 
                    ret.add(thisInt); 
                } 
            } 
            // end code that does filtering 
        } 
        return ret; 
    }



And here is the code after you've refactored using a ternary operator...


    public List filterListOfIntegersToPositives(List original, boolean inclZero) { 
        List ret = new ArrayList(original.size()); 
        // code that does filtering 
        for(int i=0; i<original.size(); i++){ 
            Integer thisInt = (Integer) original.get(i); 
            if (thisInt.compareTo(Integer.valueOf("0")) > (inclZero ? -1 : 0)) { 
                ret.add(thisInt); 
            } 
        } 
        // end code that does filtering 
        return ret; 
    }


Apologies for the mistake before - why is there no Preview post in this forum???








 Feed java.net RSS Feeds