Implemented hashCode() but retainAll() still isn't working as expected [duplicate] - java

This question already has answers here:
Java Hashset.contains() produces mysterious result
(3 answers)
Closed 4 years ago.
I have a doctor object and each object has a unique attribute "docMobile"(primary key). I made two different LinkedHashSets (doctorsByLoc & doctorsByAvail) of doctors. Now when i do a
doctorsByLoc.retainAll(doctorsByAvail)
on the two sets it deletes all the elements even though both have the same doctors.
I have implemented hashCode() Method in my doctor class. I also printed the sets individually to check in the sets have same elements.
public class Doctor{
String docName;
long docMobile;
String docLocation;
int docDays;
#Override
public int hashCode() {
return Long.hashCode(docMobile);
}
}
Then somewhere in a servlet something like this happens
public static void main(String[] args){
Set<Doctor> doctorsByLoc = new LinkedHashSet<>();
Set<Doctor> doctorsByAvail = new LinkedHashSet<>();
doctorsByLoc.add(d1);
doctorsByLoc.add(d2);
doctorsByLoc.add(d3);
doctorsByAvail.add(d1);
doctorsByAvail.add(d2);
doctorsByAvail.add(d3);
System.out.println("Before retain All "+doctorsByLoc.size());
for(Doctor d:doctorsByLoc){
System.out.println(d.getdocName());
}
doctorsByLoc.retainAll(doctorsByAvail);
System.out.println("After retain All"+doctorsByLoc.size());
for(Doctor d:doctorsByLoc){
System.out.println(d.getdocName());
}
}
Actual output:
Before retain All 3
d1's name
d2's name
d3's name
After retain All 0
How can i fix my hashcode method so that the doctors remain.
I have tried printing the hashcode before returning it and I got pairs of similar hashcode as output.

You did not override equals correctly. You should be overriding it as follows:
#Override
public boolean equals (Object other) // Not "Doctor other"
{
// implementation here
}

Related

comparator of priorityqueue in java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
Im trying to use the override comparator method of priorityqueue and i want to achieve the following:
i have the current list:
RG3
PR1
PR2
RG4
RG1
RG2
the RG refers to a regular person and the PR refers to a person with priority, the numbers represent the turns.
what i want is to get a First in first out order except when is a priority person wich will go to the top of the queue in his turn. so in the list i want the following result
PR1
PR2
RG1
RG2
RG3
RG4
heres what ive done until now:
Queue<Ficha> cola = new PriorityQueue<>(6, idComparator);
while (!list.isEmpty()) //this list is the unsorted list.
{
aux = list.remove(0);
cola.add(aux); // adds it to the priority queue
}
while(!cola.isEmpty())
{
aux = cola.poll();
System.out.println(aux.getCod_priority()+aux.getTurn()); // this shows me the order of the queue
}
}
public static Comparator<Ficha> idComparator = new Comparator<Ficha>()
{
#Override
public int compare(Ficha f1, Ficha f2) {
return (int) ((f1.getTurn()+prioridad(f1.getCod_priority())) - (f2.getTurn()+prioridad(f2.getCod_priority())));
}
};
private static long prioridad(String cod_priority) // this method i use it to give the cod_priority a int value to compare
{
if(cod_tipo_ficha=="PR")
{
return 10000;
}
else
{
return 1;
}
}
and when i run it i get the following order:
PR1
RG1
RG2
PR2
RG3
RG4
i know my problem is in the comparator method but i dont know how to achieve the queue that i want.
i know theres a lot of question related of how to compare but the only answers i see is when you compare strings. and this one i need to compare the priority string and the int.
Just change cod_tipo_ficha=="PR" to
if("PR".equals(cod_tipo_ficha)) {
...
}
Should work

How to print List's object elements in Java? [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
I have something like the following:
List<Interval> intervals = new LinkedList<Interval>();
intervals.add(new Interval(1));
intervals.add(new Interval(2));
How can I print the List intervals? I attempted System.out.println(intervals), but it simply returns [Interval#...].
Thank you
The issue is not in printing the List but in printing the Interval.
Implement Interval.toString() method.
System.out.println(intervals) will call .toString() method of the object you are trying to print, which is List.
In order to print every object you have to override the toString() method for Interval or print specific value.
for (Inteval interval : intervals) { System.out.println(interval.getValue());}
or if you override the toString() method for Interval
for (Inteval interval : intervals) { System.out.println(interval);}
You can override the toString() as follows:
public class Interval {
public int value;
public String val;
#Override
public String toString() {
return "Value string: " + val + " value int: " + value;
}
}

Does PriorityQueue maintain natural order? [duplicate]

This question already has answers here:
Print content of priority queue
(3 answers)
Closed 7 years ago.
The elements of the priority queue are ordered according to their
natural ordering, or by a Comparator provided at queue construction
time, depending on which constructor is used.
However, in the following example, when I print the whole queue at once, the queue's elements are printed in random order. On the other hand, if I poll the elements one by one they are printed in natural order.
Could someone explain me this ambiguious behavior? Or Am I missing something?
public class QueueExample {
public static class Employee implements Comparable<Employee>{
private int id;
private String name;
public Employee(int id, String name){
this.id=id;
this.name=name;
}
public String toString(){
return "id:"+id+" name:"+name;
}
public int compareTo(Employee emp){
return name.compareTo(emp.name);
}
}
public static void main(String[] args) {
Queue<Employee> priority=new PriorityQueue<Employee>();
priority.add(new Employee(101, "Atlas"));
priority.add(new Employee(102, "Ztlas"));
priority.add(new Employee(101, "Ftlas"));
priority.add(new Employee(101, "Ptlas"));
System.out.println(priority);
System.out.println(priority.poll());
System.out.println(priority.poll());
System.out.println(priority.poll());
System.out.println(priority.poll());
}
}
Output:
[id:101 name:Atlas, id:101 name:Ptlas, id:101 name:Ftlas, id:102
name:Ztlas]
id:101 name:Atlas
id:101 name:Ftlas
id:101 name:Ptlas
id:102 name:Ztlas
A bit further down in the documentation it says:
The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order.
Since AbstractCollection's toString (which PriorityQueue inherits) returns a string in the iteration order, you get no particular order from it.

Array prints memory address despite Override [duplicate]

This question already has answers here:
I am getting the memory address from an arraylist, need info
(2 answers)
Closed 8 years ago.
Now, I want it to only print what it says, without the memory address as well. How would I achieve that?
public Telefonnummer[] getTelenummer() {
Telefonnummer[] tnummer = new Telefonnummer[nummerarray.size()];
nummerarray.toArray(tnummer);
System.out.println(Arrays.toString(tnummer) );
return tnummer;
}
Is the constructor and:
private static void kundSök() {
System.out.println("...? ");
String namn = keyboard.nextLine();
if (kunderna.containsKey(namn)) {
for (String k : kunderna.keySet()) {
Kund kund = kunderna.get(k);
System.out.println(kund);
System.out.println(kund.getTelenummer());
After i have added a person to the ArrayList etc it gives me an output of:
Sam wasdfgn
[123456: efdg]
[LTelefonnummer;#28d93b30
The last part, memory address bit, is the part I want to get rid of.
Yet again, how do i achieve that?
Edit: I tried to Override, but it did not do anything at all. Could there be another problem?
The default behaviour for toString is to print the type name (as L followed by the type name), followed by # and the hexString of the hashCode (which by default is the memory address for the object).
To change this, override the toString method for your Telefonnummer class.
public class Telefonnummer {
private String nummer;
...
#Override public String toString() {
return "Dial " + nummer + " for a good time";
}
}
Guava library has Joiner which can be used for that. See https://code.google.com/p/guava-libraries/wiki/StringsExplained
String str = Joiner.on(",").join(list);
You also have to have working toString function on class for elements of the list

Sort class by field and by size of value [duplicate]

This question already has answers here:
sort and group a java collection
(5 answers)
Closed 8 years ago.
Good morning. I have class, which contain data in this format: [int][Object]. I never worked with classes, i usually use Lists, Maps, now i don't understand how to implement this in common classes. How to sort by field in classes?
Be careful , my toString only showing field code without field number.
I would like to sort this class by size of value[Object]
( "1 1234", "2 35881", ... "7 22" --> "7 22", "1 1234", "2 35881")
public class Record {
private int number;
private Object code;
... Getters/Setters
#Override
public String toString() {
return (String)(this.code);
}
}
public class Storage
{
List<Record> record;
public Storage(){
this.record = new ArrayList<Record>();
}
public void addRecord(Record record) {
this.record.add(record);
}
public Record getRecord(int number){
return this.record.get(number);
}
public void delRecord(int number){
this.record.remove(number);
}
public Integer sizeStorage(){
return record.size();
}
}
public class Start {
public static void main(String[] args) {
System.out.println("Start reading from Xls");
ReaderXls read = new ReaderXls();
Storage storageRZS = readrzs.ReadXls("Text1obj",2,12);
.....
System.out.println(storageRZS.getRecord(5));
System.out.println(storageRZS.getRecord(7));
System.out.println(storageRZS.getRecord(10));
2122
189266
244
The result should be this:
244
2122
189266
If you wissh to access records in an ordered way you will need to use a comparator or implement comparable in your Record class.
Sample:
Collections.sort(listOfRecords, new Comparator<Record>() {
#Override
public int compare(Record o1, Record o2) {
//null checks
/*Compare the object field according to your custom logic.
Here it is assumed that getObjectCodeAsInt() will return an integer equivalent of the objectCode.*/
if(o1.getObjectCodeAsInt() > o2.getObjectCodeAsInt())
return 1;
else if(o1.getObjectCodeAsInt() < o2.getObjectCodeAsInt())
return -1;
return 0;
}
});
You will need to make a customer Comparator for the same. Read how to sort user defined objects
I am little unsure about the exactness of the question.
However if you wish to sort the collection such as list by different class attributes (fields as you say), you may look into Collections.sort
You will need to implement the Comparator interface for each of sorting attribute.
Regards
VJ

Categories