Comparing objects never returns true

I'm trying to compare two objects of the same type (in method doesHave), but I've never got "true" returned. Here's my code:

private ArrayList<Osoba> osoba = new ArrayList<Osoba>(); public boolean doesHave(Osoba o) { for (int i = 0; i < osoba.size(); i++) { if (pobierz(i).equals(o)) return true; } return false; } public Osoba pobierz(int index) { return osoba.get(index); }

The 'Osoba' class, looks like this:

public class Osoba { private String imie; private String nazwisko; public String toString() { return imie + " " + nazwisko; } public Osoba(String name, String surname) { imie = name; nazwisko = surname; } public String getImie() { return imie; } public String getNazwisko() { return nazwisko; } }

Code from main:

Osoba osoby = new Osoba(name, surname); if (kartoteka.doesHave(osoby) == Boolean.TRUE) { temp = odczyt.nextLine(); if (temp.equals("y")) kartoteka.usun(osoby); //some method else ... }

No matter what input I'd use, this part never happens. 'kartoteka' is my package which of course I have imported. Each class is in separate package, but there is no problem with using them. I've tried googling it for quite some time, but nothing helped me, it just seems like

if (kartoteka.doesHave(osoby) == Boolean.TRUE)

Is never true, but I have no idea why. Code without Boolean.TRUE doesn't work as well. If I could get some hints, I'd be thankful. Sorry for asking that kind of question, but I'm new in java.

-------------Problems Reply------------

Imagine that you and your wife have twins.

Are they the "same" person? No, they are not. Lets call them twin A and twin B. They are two different instances, yes, they look same, but if you are talking twin A, you are not talking about twin B and vice versa. The point is, they are not EQUAL :), it is same in Java. Twin A is equal only to itself, no1 else.

You have to create your own method, which compares all properties of two instances of Osoba.

The other option is to override the equals and hashCode methods, but it is not good approach in your case.

Right now your code checks if the memory address of two objects is the same which can only be true if it is the same exact object.

You need to implement a method that compares two Osoba objects by comparing whichever properties you want from these objects and returning true/false appropriately.

Osaba should implement equals:

public boolean equals(Object other) {
return imie.equals(((Osaba) other).getImie())
&& nazwisko.equals(((Osaba) other).getNazwisko()));

If you do not implement equals, the default implementation will be used.

Responds from @libik and @Code Whisperer helped me, so if anyone has the same problem, read and try to understand, it helped for me. I like that twins allegory :) It's kind of the same situation when I tried to compare two Strings.

Category:java Views:4 Time:2017-09-09
Tags: java

Related post

Copyright (C), All Rights Reserved.

processed in 0.117 (s). 11 q(s)