0
package no.hiof.suzdarbi.oblig4;

import java.time.LocalDate;
import java.util.ArrayList;

public class Film extends Produksjon implements Comparable{

    public Film(String tittel, String beskrivelse, double spilleTid, LocalDate utgivelsesDatoo, Person regissor){
        super(tittel,beskrivelse,spilleTid,utgivelsesDatoo,regissor);
        FilmListe.add(this);
    }


    public static ArrayList<Film> FilmListe = new ArrayList<Film>();
    @Override
    public String toString() {
        return "Film tittel: " + tittel + '\n' +
               "Beskrivelse av filmen: " + beskrivelse + '\n' +
               "Spilletid: " + spilleTid + " minutter" + '\n' +
               "Utgivelsesdato: " + utgivelsesDatoo + '\n' +
               "Regissør: " + regissor.hentNavn() + '\n';
    }    

    @Override
    public int compareTo(Object o) {
        return 0;
    }
}

Hello, Im currently making a simple Film program, here i want use compareTo to sort my arraylist alphabetically. So Films From A-Z, and I'm not quite sure how to implement this in my compareTo

Arun Sudhakaran
  • 2,167
  • 4
  • 27
  • 52
  • 1
    Possible duplicate of [compareTo method java](https://stackoverflow.com/questions/10017381/compareto-method-java) – Rann Lifshitz Feb 20 '18 at 11:21
  • What are you not sure about ? Have you check the [javadoc](https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html) ? Please [edit] the question to be more specific. See [ask] if needed – AxelH Feb 20 '18 at 11:21
  • @AxelH I basically want to sort my Films in an alphabetically order using compareTo. In the top you can already see I'm using "Implements Comparable" – Suzdar Zeni Feb 20 '18 at 11:24
  • So you have a `Collection` somewhere that you `sort` ? You just need to be able to compare two instance of Film. In general, you can simply compare the variable you want like `this.tittel.compareTo(o.tittel)` (you will need to cast the parameter `o`). Find a short tutorial to try first, then if you are still stuck, I will help you. Check the duplicate question, it will be the same idea. – AxelH Feb 20 '18 at 11:27

2 Answers2

1

You need to typecast object o to Film object. Then you can compare the title of both the films using String's compareTo method.

So compareTo(Object o) code would be like this

public int compareTo(Object o) {
    Film film = (Film)o;
    return this.title1.compareTo(film.title1);
}
paras_47
  • 21
  • 5
0

Please read docs for Arrays.sort(Object[]):

From docs:

Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. All elements in the array must implement the Comparable interface. Furthermore, all elements in the array must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the array).

The sort method does rely on the Comparable interface of the array elements