Checking equality of three or more Strings in Java -


i know basic question, trying find ways make code clean , concise possible. there way compare equality of 3 or more strings in single if() statement? using && operator progressively compare each string. however, imagine, between long variable names , methods being called, these if() statements cluttered quickly. additionally planning have unknown number of these strings, , avoid complex for loops cluttered if()s nested inside of them. code looks like:

string = new string("a"); string b = new string("b"); string c = new string("c"); if(a.equals(b) && b.equals(c)) {     dosomething(); } 

is there way, or collection of sort can use allow me compare these values more this:

if(a.equals(b).equals(c)) {     dosomething(); } 

there no simple way chain equals() commands this. in order able chain them way, equals() have return reference string itself. then, however, can't return boolean value represents outcome of comparison anymore.

also, see not particularly problematic compare 3 strings separately in first example. make sure keep code formatted, , remain easy understand, longer variable names:

if(myvalueawithalongname.equals(myvaluebwithalongname) &&    myvaluebwithalongname.equals(myvaluecwithalongname) &&    myvaluecwithalongname.equals(myvaluedwithalongname) &&    ... ) { 

alternatively, use 1 of other solutions proposed in thread , wrap values collection , write helper method. note might have negative impact on memory usage, performance , possibly readablity.


on side note, should never create strings using constructor new string(). assign string literal directly variable:

string = "a"; 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

node.js - Using Node without global install -

php - CakePHP HttpSockets send array of paramms -