andrej tetovo
andrej tetovo

Reputation: 13

Java code doesn't output expected results

I am writing code about an Audition with candidates from different towns. For that purpose i use HashMap and TreeSet. Now the TreeSet cannot contain duplicate obj as ive overloaded equals method in Participant class. However the Set adds them anyway. Is there any way i can fix this?

I have tried anything i can think of and i cannot find related posts to my questions.

the code:

package audition;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;


class Audition {
    Map<String,TreeSet<Participant>>participants;
    public Audition() {
        participants=new HashMap<String,TreeSet<Participant>>();
    }
    void addParticpant(String city, String code, String name, int age) {
        Participant p=new Participant(code,name,age);
        if(participants.get(city)==null) {
            participants.put(city, new TreeSet<Participant>() {

                private static final long serialVersionUID = 1L;

                @Override
                public String toString() {
                    StringBuilder sb=new StringBuilder();
                    int br=0;
                    for(Participant p:this) {
                        if(br==this.size()-1)break;
                        br++;
                        sb.append(p).append('\n');
                    }
                    sb.append(this.last());
                    return sb.toString();
                }
            }); 
            participants.get(city).add(p);
        }
        else {

            participants.get(city).add(p);
        }
    }
    void listByCity(String city) {
        System.out.println(participants.get(city));
    }
}

class Participant implements Comparable<Participant>{
    String code;
    String name;
    int age;
    public Participant(String code, String name, int age) {
        this.code = code;
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        Participant p=(Participant)o;
        return this.code.equals(p.code);
    }

    @Override
    public int compareTo(Participant o) {
        // TODO Auto-generated method stub
        if(this.name.compareTo(o.name)==0) {
            return Integer.compare(this.age, o.age);
        }
        return this.name.compareTo(o.name);
    }
    @Override
    public String toString() {
        return code+" "+name+" "+String.valueOf(age);
    }

}
public class AuditionTest {
    public static void main(String[] args) {

        Audition audition = new Audition();
        List<String> cities = new ArrayList<String>();
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            String[] parts = line.split(";");
            if (parts.length > 1) {
                audition.addParticpant(parts[0], parts[1], parts[2],
                        Integer.parseInt(parts[3]));
            } else {
                cities.add(line);
            }
        }
        for (String city : cities) {
            System.out.printf("+++++ %s +++++\n", city);
            audition.listByCity(city);
        }
        scanner.close();
    }
}

> Input: 
> Скопје;001;Ана;17 
> Скопје;002;Борис;19 
> Скопје;002;Иван;15
> Скопје;003;Јована;23 
> Скопје;004;Михаела;18 
> Битола;002;Николина;17
> Битола;001;Стефанија;16 
> Битола;001;Елена;19 
> Битола;005;Анастасија;21
> Битола;004;Игор;20 
> Гевгелија;003;Аце;17 
> Гевгелија;001;Иван;25
> Гевгелија;002;Мартина;15 
> Гевгелија;005;Наташа;19 
> Гевгелија 
> Битола
> Скопје



> my Output:
> +++++ Гевгелија +++++ 
> 003 Аце 17 
> 001 Иван 25 
> 002 Мартина 15 
> 005 Наташа 19
> +++++ Битола +++++ 
> 005 Анастасија 21 
> 001 Елена 19 
> 004 Игор 20 
> 002 Николина 17 
> 001 Стефанија 16
> +++++ Скопје +++++ 
> 003 Јована 23 
> 001 Ана 17  
> 002 Борис 19 
> 002 Иван 15 
> 004 Михаела 18


> expected Output:
> +++++ Гевгелија +++++ 
> 003 Аце 17 
> 001 Иван 25 
> 002 Мартина 15 
> 005 Наташа 19
> +++++ Битола +++++ 
> 005 Анастасија 21 
> 004 Игор 20 
> 002 Николина 17 
> 001 Стефанија 16
> +++++ Скопје +++++ 
> 003 Јована 23 
> 001 Ана 17 
> 002 Борис 19 
> 004 Михаела 18

the code is written in cyrillic(not important)

Upvotes: 0

Views: 65

Answers (2)

davidxxx
davidxxx

Reputation: 131526

Your compareTo() method is incorrect according to your expected.
You want to have distinct Participant codes in your expected.
So compareTo() should be :

@Override
public int compareTo(Participant o) {    
    return code.compareTo(o.code);
}

Note that the Comparable javadoc says that :

It is strongly recommended (though not required) that natural orderings be consistent with equals.

With this change it will be the case.
Note also that hashCode() should also be overriden consistently if you override equals().

Upvotes: 1

Joe C
Joe C

Reputation: 15714

A TreeSet does not use equals to determine, for its purpose, whether two objects are equal. It instead uses compareTo and if that equals zero, it considers the two objects to be equal.

You therefore need to ensure that what you compare in equals and what you compare in compareTo match.

Upvotes: 1

Related Questions