#Generic Comparator question

1 messages ยท Page 1 of 1 (latest)

sour pineBOT
#

<@&987246399047479336> please have a look, thanks.

#

Here is an AI assisted attempt to answer your question ๐Ÿค–. Maybe it helps! In any case, a human is on the way ๐Ÿ‘. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.

#
TJ-Bot
I need to make a class that implements a generic method that accepts a generic ArrayList as a variable, and sorts it. the class itself doesn't implement comparable but the list types do implement comparable. the assignment explicitly says not to implement

method should accept a Comparator as a parameter to determine the sorting order.

Here's an example implementation of such a class:

import java.util.ArrayList;
import java.util.Comparator;

public class GenericSorter {

    public <T> void sort(ArrayList<T> list, Comparator<? super T> comparator) {
        list.sort(comparator);
    }

    public static void main(String[] args) {
        ArrayList<Integer> intList = new ArrayList<>();
        intList.add(3);
        intList.add(1);
        intList.add(2);

        GenericSorter sorter = new GenericSorter();
        sorter.sort(intList, Comparator.naturalOrder());

        System.out.println(intList); // Output: [1, 2, 3]
    }
}

In this example, the sort method accepts an ArrayList<T> and a Comparator<? super T> as parameters. The method uses the sort method from the ArrayList class to sort the list based on the provided comparator.

This approach allows you to sort generic lists without requiring the elements to implement Comparable, making it more flexible and reusable across different types.

crude osprey
#

public <T> void sort(ArrayList<T> list, Comparator<? super T> comparator) {
list.sort(comparator);
}
chat gpt suggested thaht, but i don't understand whats going on here

faint cobalt
#

I don't understand
There is already a method like this

crude osprey
#

What do you mean by that?

faint cobalt
#

There is already a sort method

#

in the class ArrayList

crude osprey
#

for generic types too?

faint cobalt
#

yes ?

#

why wouldn't it be generic ?

crude osprey
#

but, how does it sort them

#

by what variable

faint cobalt
crude osprey
#

Well, when sorting a list, you sort by something

#

if i don't implement a comparator how does it know what to sort by?

faint cobalt
crude osprey
#

i can't

#

i have 2 classes in my package, one of them has a comparator implemnted, and the other doesn't, the assignment tells me to create a new class
that contains a method to sort a generic ArrayList using compareTo

faint cobalt
#

ah

crude osprey
#

but the class itself doesn't implement it

faint cobalt
#

so you have to make your own sort method

crude osprey
#

which why i am confused

faint cobalt
crude osprey
#

for genertic types?

#

not sure how peepo_think

#

Cause i don't know what to compare them by

faint cobalt
#

then generify it later

faint cobalt
#

as your assignment said

crude osprey
#

but i need a "Generic" compareTo

faint cobalt
#

as I said

#

it doesn't matter

#

compareTo is be definition generic

crude osprey
sour pineBOT
crude osprey
#
package carDealership;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class Employee implements Comparable{
    private String name;
    private int id;
    private int salesNum;
    public Employee(String name,int id,int salesNum){
        if (Integer.toString(id).length()!=9){
            throw new IllegalArgumentException("Not a valid ID, please enter a 9 digit ID");
        }
        if (name.matches("[a-zA-Z]+")){
            throw new IllegalArgumentException("Not a valid name, Please enter only english letters");
        }
        if (salesNum<0){
            throw new IllegalArgumentException("Not a vaild sales Number, please enter a non-negative integer");
        }
        this.name=name;
        this.id=id;
        this.salesNum=salesNum;
    }

    public void sellCar(Car car,String path){
        File myObj = new File(path);
        try {
            FileWriter myWriter = new FileWriter(path,true);
            myWriter.write(car.toString());
            myWriter.close();

        } catch (IOException e) {
            throw new RuntimeException("An error occured");
        }
        salesNum++;
        Car.soldCars(car);
    }
    public int calcSalary(){
        return 6000+salesNum*100;
    }

    @Override
    public String toString() {
        return "Name: "+ name+", ID: "+ id+", Number of sales done: "+salesNum+", Salary this month:" + calcSalary();
    }


    public int compareTo(Employee other) {
        return Integer.compare(this.salesNum,other.salesNum);
    }

    @Override
    public int compareTo(Object o) {
        Employee other = (Employee) o;
        return Integer.compare(this.salesNum,other.salesNum);
    }
}
sour pineBOT
crude osprey
#

this is my second class

faint cobalt
crude osprey
#
package carDealership;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;

public class CarDealership{
    public static <T> void sortDescending(ArrayList<T> list){
        list.sort(comparator);
    }

}

this is the class i need to make now

sour pineBOT
crude osprey
faint cobalt
faint cobalt
crude osprey
faint cobalt
crude osprey
#

what's the difference between now and before

#

having that <Employee>

faint cobalt
#

Because now you compare employees

crude osprey
#

ohh, no generic objects

#

yeahh, my bad

#

so if i want to sort a generic list, by not knowing what to sort by

#

how can i sort it

faint cobalt
#

by using compareTo

crude osprey
#

of the generic object?

faint cobalt
#

yes

crude osprey
#

can you give me an example?

#

how can i access the compare to of the generic type?

faint cobalt
#

by calling compareTo

#

obj1.compareTo(obj2)

crude osprey
#

so i`ll just bubble sort it

#

easiet one

#

i can't use compareTo

#

its like it doesn't exist

faint cobalt
#

yes

#

you need to declare T correctly

crude osprey
#

does my method need to implement the comparable interface?

faint cobalt
#

no it wouldn't make sense

#

You have to tell java

crude osprey
#

public static <T> void sortDescending(ArrayList<T> list)

faint cobalt
#

that T must implement Comparable

#

so only an ArrayList of elements that implement Comparable can be sent to this sort method

crude osprey
#

public static <T extends Comparable<T>> void sortDescending(ArrayList<T> list){

faint cobalt
#

yes

crude osprey
#

what's the difference between extends and implements?

faint cobalt
#

in a class declaration

#

you extends classes

#

you implement interfaces

#

in a generic declaration, it's always extend no matter if it is a class or interface

crude osprey
#

extends is for daughter classes

#

or subclasses

#

so Subclass extends SuperClass

#

so a generic always extends, that's whyh it was weird to me

#

Thank you!

#
    public static <T extends Comparable<T>> void sortDescending(ArrayList<T> list){
        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < list.size()-1; j++) {
                T now = list.get(j);
                T next = list.get(j+1);
                if (now.compareTo(next)<0){
                    list.set(j,next);
                    list.set(j+1,now);
                }
            }
        }
    }
sour pineBOT
faint cobalt
crude osprey
#

nothing to try it on yet haha

#

let me write the rest of the main

#

i`ll chehck

faint cobalt
# crude osprey nothing to try it on yet haha

Try it with numbers first

ArrayList<Integer> list = IntStream.range(0, 100).boxed().collect(Collectors.toCollection(ArrayList::new));
Collections.shuffle(list);
System.out.println(list);
CarDealership.sortDescending(list);
System.out.println(list);

Try this

crude osprey
#

[99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

#

this is the output

#

so it works ๐Ÿ™‚

#

Thank you very much!

faint cobalt
crude osprey
#

now i need to go learn how to read and write to text files to continue

#

ohh right, i`ll check with the employees

#

works great!

#
ArrayList<Employee> employees = new ArrayList<>();
        employees.add(new Employee("Yossi",456548123,1));
        employees.add(new Employee("Omer",128745965,5));
        System.out.println(employees);
sour pineBOT
faint cobalt
#

It didn't change the order

#

find a better test

crude osprey
#

i just chnaged the numbers

#

and it sorted thehm

#
    public static void main(String[] args) {
        ArrayList<Employee> employees = new ArrayList<>();
        employees.add(new Employee("Yossi",456548123,5));
        employees.add(new Employee("Omer",128745965,6));
        sortDescending(employees);
        System.out.println(employees);
sour pineBOT
crude osprey
#

[Name: Omer, ID: 128745965, Number of sales done: 6, Salary this month:6600, Name: Yossi, ID: 456548123, Number of sales done: 5, Salary this month:6500]

#

[Name: Yossi, ID: 456548123, Number of sales done: 5, Salary this month:6500, Name: Omer, ID: 128745965, Number of sales done: 4, Salary this month:6400]

#

changed omer from 6 to 4 sales, and it changed

faint cobalt
#

same order

#

Yossi is still first

crude osprey
#

Omer was first

#

since he had more sales

#

now Yossi has more, so hes first

#

same input order

faint cobalt
#

But he was already first

#

yes same input order

#

so you have no way to tell if it worked

#

add at least two other

#

and don't put them in order

crude osprey
#
public static void main(String[] args) {
        ArrayList<Employee> employees = new ArrayList<>();
        employees.add(new Employee("Yossi",456548123,5));
        employees.add(new Employee("Omer",128745965,4));
        employees.add(new Employee("Omerr",128745965,20));
        employees.add(new Employee("Omerrr",128745965,13));
        sortDescending(employees);
        for (Employee employee:employees){
            System.out.println(employee);
        }

    }
sour pineBOT
crude osprey
#

Name: Omerr, ID: 128745965, Number of sales done: 20, Salary this month:8000
Name: Omerrr, ID: 128745965, Number of sales done: 13, Salary this month:7300
Name: Yossi, ID: 456548123, Number of sales done: 5, Salary this month:6500
Name: Omer, ID: 128745965, Number of sales done: 4, Salary this month:6400

faint cobalt
#

right

crude osprey
#

Thank you very much Alathreon