Friends, help translate a function written in JavaScript into Java so that the function accepts both arrays and string variables.

Thank.

function str_replace ( search, replace, subject ) { if(!(replace instanceof Array)){ replace=new Array(replace); if(search instanceof Array){ while(search.length>replace.length){ replace[replace.length]=replace[0]; } } } if(!(search instanceof Array))search=new Array(search); while(search.length>replace.length){ replace[replace.length]=""; } if(subject instanceof Array){ for(k in subject){ subject[k]=str_replace(search,replace,subject[k]); } return subject; } for(var k=0; k<search.length; k++){ var i = subject.indexOf(search[k]); while(i>-1){ subject = subject.replace(search[k], replace[k]); i = subject.indexOf(search[k],i); } } return subject; } 
  • Why the hell might it be needed in java? - alexlz

2 answers 2

And what is the complexity of sobsno not really understand ...

1) The role of Array in Java will be played by ArrayList<String>

2) The replacement function must be declared as function str_replace (Object search, Object replace, Object subject);

3) Type casting should be performed by entering through the casting of the type ((ArrayList<String> )search).size() is instead of search.length , etc.

I do not deliberately cite the full code, because it contradicts the forum rules.

  • Thanks for the answer, but ideally you would see a working version, further understanding. I'm weak in Java. - mkw
  • It is not true, there is no function in Java) Apparently, there should be a void. - Ivan Bartsov

In Java, strict typing means that by the time this magic method is called, the types of all arguments are most likely known (unless they are intentionally lost at some point).

Strictly speaking, it is possible to do the same method in Java, but the presence of such a task is a sign that somewhere in another place something is written incorrectly - where do you get the data without knowing a string or an array? (It happens when the JSON serializer on the server is poorly written and serializes an array from one element to just one element - uh kapets, it’s hard for it)

Secondly, it makes no sense to reinvent the wheel - there is a fancy Apache Commons Lang library, and there is a class in it: StringUtils , see the replaceEach(...) method

The method accepts String[] , it remains to make sure that when you call it, you have either an array of strings or an array of one string.