3

I have an object array containing two fields per object. I have to write a method that will sort my array by the first field. I already have a method which extracts the first field from each object

I always get an error message when I call my method to sort.

Here is my code:

public static void trier(String[]code, String[]nom, int nbObj) {
    for(int i = 0; i < nbObj-1; i++) {
        int indMin = i;
        for (int j = i+1; j < nbObj; j++)
            if (code[j].compareTo(code[indMin]) < 0)
                indMin = j;
        if (indMin != i) {
            // permutation :
            String tempo = code[i];
            code[i] = code[indMin];
            code[indMin] = tempo;
    
            // permutation :
            String temp = nom[i];
            nom[i] = nom[indMin];
            nom[indMin] = temp;
        }
    }
}

and the call :

Classe.trier(tableau, tableau, nbObj);

I also tried Class.sort(array.getCode(), array.getName(), nbStudent);

But I still have compilation errors

thank you in advance for your help

2
  • 1
    Reformat your code, please Commented Aug 20, 2020 at 12:49
  • 1
    What errors do you have? And can you show how/where you define the variables tableau and nbObj? Commented Aug 20, 2020 at 12:53

1 Answer 1

3

First of all, you don't have to use 2 separate arrays to contain your data. You can put everything in a single array, but better way is to use Java Collections. Perfect choice is ArrayList. However, you still better combine two fields into a single object. You can do it like this:

public class MyObject {
    String code;
    String nom;

    MyObject(String code, String nom) {
        this.code = code;
        this.nom = nom;
    }
}

Now you have a class containing 2 fields. Your aim is to sort a collection of such objects by their second field (nom). You can do this easily since Java 8:

public static void sort1(ArrayList<MyObject> list) {
    list.sort((obj1, obj2) -> obj1.nom.compareTo(obj2.nom));
}

Or

public static void sort2(ArrayList<MyObject> list) {
    list.sort(Comparator.comparing(MyObject::getNom));
} // However for this you need to add method getNom to MyObject

Remember to put your objects in the collection properly. For example:

MyObject a = new MyObject("abc", "abide");
MyObject b = new MyObject("cab", "whatever you want");

ArrayList<MyObject> list = new ArrayList<>();
list.add(a);
list.add(b);
trier(list);
Sign up to request clarification or add additional context in comments.

1 Comment

@toatyohan you are welcome :) Don't hesitate to accept my answer if it helped you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.