Path: csiph.com!aioe.org!.POSTED!not-for-mail From: =?UTF-8?Q?Arne_Vajh=c3=b8j?= Newsgroups: comp.lang.java.programmer Subject: Re: Comparison structure? Date: Tue, 4 Oct 2016 20:16:21 -0400 Organization: Aioe.org NNTP Server Lines: 81 Message-ID: References: <59c17fe5-61a6-46dc-918f-ee5aa348e3fd@googlegroups.com> NNTP-Posting-Host: PBuS014lhzVyHjLbXmo/ZQ.user.gioia.aioe.org Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit X-Complaints-To: abuse@aioe.org User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Thunderbird/45.3.0 X-Notice: Filtered by postfilter v. 0.8.2 Xref: csiph.com comp.lang.java.programmer:35721 On 10/4/2016 3:35 PM, Eric Sosman wrote: > On 10/4/2016 1:29 PM, Eric Douglas wrote: >> On Tuesday, October 4, 2016 at 12:53:51 PM UTC-4, Roedy Green wrote: >>>> Is there a better structure? >>> the only alternative I can think of is to use a compare method that >>> returns +1 -1 0. >>> Then you could use a switch. >> >> In that case you'd have to override the compareTo? >> I read the doc on that method and it says returns a zero, or a value >> less than or greater than zero. If it's not guaranteed to return >> specific values for less than or greater than, what would be the >> switch case? >> This seems at least one reason people in the following thread suggest >> sticking with the 3-way if. >> http://stackoverflow.com/questions/18510360/how-to-use-greater-than-or-equal-in-a-switch-statement >> >> >> Otherwise that code would be equivalent to >> Integer compareMe = 1; >> int compareTo = 2; >> final int assignMe; >> switch (compareMe.compareTo(compareTo)) { >> case 0: >> assignMe = 4; >> break; >> case 1: >> assignMe = compareMe + 2; >> break; >> case -1: >> assignMe = compareMe; >> break; >> } >> >> Of course Integer is final so you couldn't even just subclass it to >> override compareTo. Without having 3 certain return values, this >> method ends up uglier. > > You could use some static methods of Integer to eliminate > the Integer object instances and fix the range problem: > > int compareMe = 1; > int compareTo = 2; > final int assignMe; > switch(Integer.signum(Integer.compare(compareMe, compareTo))) { > case 0: > assignMe = 4; > break; > case 1: > assignMe = compareMe + 2; > break; > default: // not "case -1:" > assignMe = compareMe; > break; > } > > However, I'd be disinclined to call this an "improvement" over > the original code. Well - if one is competing in a code obfuscation contest then I will suggest: int compareMe = 1; final int assignMe = cases[Integer.signum(compareMe - compareTo) + 1].option(compareMe, compareTo); int compareTo = 2; with: @FunctionalInterface private interface Case { public int option(int compareMe, int compareTo); } private static Case[] cases = { (me,to) -> me, (me,to) -> 4, (me,to) -> me + 2 }; :-) Arne