Sam Brotherton Sam Brotherton - 3 months ago 9
Java Question

Java objects and 2D arrays

I am working on my A-Level computing project, and I have a 2D array, with in the x direction name, password, state (just a variable). I want to sort the 2D array using a bubble sort so that I can implement a binary search on the data. Here is the code I have come up with:

public String[][] sort(String[][] details, int len){
boolean flag = false;
String[] temp = new String[3];
int z=0;
do{
flag = false;
for (int i = 0; i < len; i++){
if(details[0][i].charAt(0) > details[0][i + 1].charAt(0)){
flag = true;
temp[0] = details[0][i];
temp[1] = details[1][i];
temp[2] = details[2][i];
details[0][i] = details[0][i + 1];
details[1][i] = details[1][i + 1];
details[2][i] = details[2][i + 1];
details[0][i + 1] = temp[0];
details[1][i + 1] = temp[1];
details[2][i + 1] = temp[2];
}
}
len--;
} while (flag);
return details;
}


However it has sort of come to my attention I could do this much easier using object orientation which is something I would love to try and have a go at. Does anyone know where I could start learning about object orientation in this sort of context, the guides I have searched for online, just talk about shapes etc... and I am really not sure how to implement those guides into this situation.

From my understanding, what I could do is set up an object with three variables, name, password and state; and when I called upon a name, I could also get the details for the password and state. Am I along the right lines here? and if so can anyone show me how I can do this please.

Thanks a lot.

Sam

Answer

Make a Detail class that stores the details you are currently storing in an array. Something like:

public class Detail {
  public String name;
  public String password;
  public String state;
}

Then modify your existing code to work with Detail objects instead of arrays of arrays.

public Detail[] sort(Detail[] details){
    boolean flag = false;
    do{
        flag = false;
        for (int i = 0; i < details.length; i++){
            if(details[i].name.compareTo(details[i + 1].name) > 0){
                flag = true;
                Detail temp = details[i];
                details[i] = details[i + 1];
                details[i + 1] = temp;
            }
        }
        len--;
    } while (flag);
    return details;
}

Note that it would be even better to just use a library function to sort the array, but if you want to do it this way to learn about bubble sort, that's fine.

Comments