0

I have a method which takes an ArrayList<Song> as argument. the class song has different methods like getTitle(), getInterpret(), toString(), toString2()...

public class Song implements Comparable<Song>{

    private String title;
    private String interpret;
    
    public Song(String title,String interpret){
        
        this.title=title;
        this.interpret=interpret;
        
    }

    public String getTitle() {
        return title;
    }

    public String getInterpret() {
        return interpret;
    }

    
    public String toString2(){
        return title+" - "+interpret;
    }

    @Override
    public int compareTo(Song otherSong) {
        
        return title.compareToIgnoreCase(otherSong.getTitle());
    }

    public String toString() {
        
        return interpret+" - "+title;
    }

}

the method printList takes an ArrayList of Song as argument:

public <Song> void printList(ArrayList<Song> songList,String sortBy){
    
    JLabel track;
            
    for(int i=0;i<songList.size();i++){

        if(sortBy=="Artist"){
        track = new JLabel("\n- "+songList.get(i).toString());}

        else if(sortBy=="Song"){
        track = new JLabel("\n- "+songList.get(i).toString2());}
        
    }
    

I have an error on songList.get(i).toString2(), the method toString2() is undefined for type Song, it seems like I can only access to the method of the class Object.

Can somebody help please?

2
  • why do you name method toString2() ? Commented Apr 2, 2017 at 10:48
  • hi, because toString2() is just a variation of toString() Commented Apr 2, 2017 at 11:08

1 Answer 1

3

You've made your method generic, and chose to name the generic type Song. It shouldn't be generic:

public void printList(ArrayList<Song> songList,String sortBy){

Also, compare strings with equals(), not ==.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you for your answer, but when i remove the "<Song>" in the method declaration, the compiler tells me "Song cannot be resolved to a type", do you know why?

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.