2

Is this good coding in java?:

I have an String array. String[] strArr = .... Now I want to process on it and get the result, so I made a method taking a String array as an argument like,

public bopolen processArray(String[] srtArr){
   // .... some processing
   // loop over string array, process it and create a 
   // list of objects with same size as array
   List<Object> objList = new ArrayList<Object>(strArr.length);
   for(String str : strArr) {
       String[] anotherStrArr = str.split(",");
       Object myObj = new MyObject(anotherStrArr[0],anotherStrArr[1]);
       objList.add(myObj);
   }
   // .... some more processing
   // ....
   // loop over list and call another method 
   // that also takes an String array as argument like
   for (Object obj: objList) { <-- will loop same times as for the String array.
      boolean res = processData(obj.getDataMethod(), strArr); <-- again pass the same array as argument to another method. 
      // This method will get called as many time as array length.
   }
}

Now the second method:

public boolean processData(String data, String[] strArr) {
   // ..... some processing.
   // loop over String array and compare with data to process.
   for(String str: strArr) {
       String[] againStrArr = str.split(",");
       if(againStrArr[0].equals(data)) {
            // ... process on data and get the result.
       }
   }
   // ..... other statements of method.
}

So as you can see I'm passing same array to 2 methods and loop over it again and again. Is this good practice in java as my array size is very long, around 2000 elements in normal case.


Explanation on why I'm looping this much:

I got a String array from request which contains db_name and db_score of myObject which I have to update in database. Each element in strArr is comma separated db values like db_name,db_score. So first I loop over array and create a String of all names comma separated and then query in database to create List of MyObject. Then I loop over this list to update myObj with new score but to get exact score of name I again have to loop over array and compare name then get its score.


This is my table called Players:

id | name   | score
1  | mark   | 5
2  | mark_1 | 5
3  | mark_2 | 5
4  | mark_3 | 5

Sample data in string array: {"mark,10","mark_1,15","mark_2,20","mark_3,30"}

Now I iterate through array and create comma separated name string and use that in query like:

select * from myObject where name in ('mark','mark_2','mark_2','mark_3')
                                     |_________________________________|
                                                     |
                    this much part is built from looping over the String array

So first iteration is for creating where clause of query. Now this query returns List of MyObject. Second time I iterate through this list to update score of players. But to get score of particular player name I again have to iterate over strArray and find it. So for each element in list I have to call a method and pass playerName and strArr to get it's score and then finally update it in database.

Harry Joy
  • 58,650
  • 30
  • 162
  • 207
  • Only one thing I would do is, remove adding to list and call processData in processArray, that way you can eliminate another looping (unless there is specifice reason to have two methods there). – kosa Jan 16 '12 at 06:41
  • @thinksteep: the only reason to have 2 methods is the list is not built as shown here, actually it is got from database. – Harry Joy Jan 16 '12 at 06:44
  • looping through the whole array is not bad coding, but my concern is why you are actually passing the same array and looping, then populating a new ArrayList and then looping again. Maybe you should clarify what are you trying to do and then we can help you eliminate some processing. – mohdajami Jan 16 '12 at 07:13
  • Still not exactly sure what are you doing, but from the sound of it, it seems like you are doing a job that Stored Procedure or a function on database should do. So instead of all the looping, you should just pass these to the database and do all the processing on the DB side. – mohdajami Jan 16 '12 at 07:47
  • @medopal : I tried to explain the situation with example, now take a look at it. Hope you understand it. – Harry Joy Jan 16 '12 at 08:41
  • Hope my answer helps, you are free to ask for explanation – mohdajami Jan 16 '12 at 09:36

4 Answers4

1

Don't worry about it. When you pass the array, the array itself is not copied to the stack, just a reference to it. It's perfectly fine to pass the array to as many methods as you like; and the size of the array won't make any difference to the performance (except of course for within the methods themselves).

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
0

Instead of the objList You can use the array of 'MyObject' the length of this is equal to the length of the 'strArr' I guess you can use only method to process array and data and use only one for loop as the strArr is already available so the count of iteration is defined.

hakish
  • 3,990
  • 7
  • 39
  • 56
  • The list is not built as shown here, actually it is got from database so can't do as you suggest but thnx for the suggestion. – Harry Joy Jan 16 '12 at 07:05
0

Per your final explanation, no you don't need to iterate twice, here are few ways you can solve your issue:

First solution
Instead of creating the WHERE clause for all items, why not just update directly with the name being the WHERE clause. For example

loop through all names and scores (your original array)
    split the name and score
    execute an update on database(param_player_name,param_player_score)

Update statement:

UPDATE Players  
SET score = param_player_score  
WHERE name = param_player_name;

Second solution (not recommended, but just for info)
Instead of looping again, just add your objects to a HashMap instead of an array. example:

Map<String,Long> myMap = new HashMap<String,Long>();
loop through all names and scores (your original array)
     myMap.put(name,score);

That way you made the name the key of the Map, and to retrieve the score (in second loop), you just call:

Long score = myMap.get(name);

As I said, the next solution is not recommended, since it will still need you to generate a very long WHERE clause which is not a good idea, and might cause problems if number of players increases too much.

IMPORTANT NOTE
When dealing with database, always use the ID of the column instead of anything else when updating and retrieving data. So, your WHERE should filter by your id column always, supposing it's Unique and NOT NULL whereas your Name field by not be Unique and might be NULL

mohdajami
  • 9,604
  • 3
  • 32
  • 53
  • For your first solution: At first I thought the same then I realized that I can't do that cause it will open too much db sessions and might get exception as I'm using hibernate. In every iteration it will open new db session and run query then close the session. This will become much more heavy operation. I can use your second solution, this will omit going into second method and looping over strArr again. – Harry Joy Jan 16 '12 at 09:46
  • Also for your note: I know we should db_id but the problem is this string array was actually generated from a file uploaded by user on UI side. And you may know no user can know what is the db_id of particular object. – Harry Joy Jan 16 '12 at 09:48
-1

Java runtime environment has a good memory management. It even cleans unused variables when not in used... so you can even declare an array with million elements.

Netorica
  • 18,523
  • 17
  • 73
  • 108