how to check if an object already exists and return reference to that object
59 32626
Can you please describe your question in more detail?
i have to write a flower shop
i need to check if a client already exists so that i dont add a new one
[font=Verdana][size=2]your question is not yet clear.[/size][/font]
[font=Verdana][size=2]In general we compare the instance of the object with null,[/size][/font]
[font=Verdana][size=2]to see if it exists or not...[/size][/font]
i have to write a flower shop
i need to check if a client already exists so that i dont add a new one
i have to write a flower shop
i need to check if a client already exists so that i dont add a new one
Exists in what? An array, a java.util.List some other java.util.Collection?
in a list of clients
Well, read all about it in the API docs for the List.contains(...) method.
kind regards,
Jos
ps. Bookmark The API docs or download them for easy reference.
Keep those docs at your fingertips whenever you want to write code.
[code]
if(klienci.contains(klient)){
int index=klienci.indexOf(klient);
klient=klienci.get(index);
}
[code]
but it doesnt find the client in the list
can we know the errors you are getting?
[code]
if(klienci.contains(klient)){
int index=klienci.indexOf(klient);
klient=klienci.get(index);
}
[code]
but it doesnt find the client in the list
if(klienci.contains(klient)){
int index=klienci.indexOf(klient);
klient=klienci.get(index);
}
but it doesnt find the client in the list
When doing this, you're looping through the list twice: once in the contains(...) method, and another looptwhen using the indexOf(...) method.
I suggest doing this: - int index = klienci.indexOf(klient);
-
-
if(index != -1) {
-
klient = klienci.get(index);
-
}
-
else {
-
// 'klient' is not in the list 'klienci'
-
}
i get nullpointerexception
i changed it to what You suggested but it doesnt change that it doesnt find the klient in the list
the client is added to the list when a button is clicked then that client adds to the cart but before he adds to the cart i need to check if it isnt a client that already exists if it is then return him with klient = klienci.get(index);<< but it doesnt find that client
there is probably a better solution for that but unfortunately i can not think of one right one
Does your Klient class override the equals() and hashCode() methods?
kind regards,
Jos
no it doesnt shd it?
Yes it should. Read all about it in the Object.equals() and Object.hashCode()
methods documentation.
By default equality is considered reference equality and you want value equality,
e.g. if two distinct objects contain identical member values you want to consider
the two distinct objects as equal.
kind regards,
Jos
if i define an equal method for klient (client in english) how shd i use it to compare if that client already exists cos i created a list of clients and i need to find that client in a list or shd i do in in some other way
can I see how you have defined the object variable?
Did you set it to null , initially?
i get nullpointerexception
if i define an equal method for klient (client in english) how shd i use it to compare if that client already exists cos i created a list of clients and i need to find that client in a list or shd i do in in some other way
That's the convenient part of it all: the List does it for you when you call a
List.contains() of List.indexOf() method. Have a look at the contains() method:
(this is from the 1.6 JDK) -
public boolean contains(Object o) {
-
Iterator<E> e = iterator();
-
if (o==null) {
-
while (e.hasNext())
-
if (e.next()==null)
-
return true;
-
} else {
-
while (e.hasNext())
-
if (o.equals(e.next()))
-
return true;
-
}
-
return false;
-
}
See how it uses the equals() method when it needs to find an object.
kind regards,
Jos
if i define method equals for klient how i can compare if that klient(client in english) already exists i created a list of clients client doesnt inherits from any other class so i can not compare it to a class it inherits from
if i define method equals for klient how i can compare if that klient(client in english) already exists i created a list of clients client doesnt inherits from any other class so i can not compare it to a class it inherits from
Your Klient class equals() method just needs to compare your 'this' Klient
with another Klient object: -
public class Klient {
-
.
-
.
-
public boolean equals(Object obj) {
-
if (obj == null || !(obj instanceof Klient)) return false;
-
Klient that= (Klient)obj;
-
// compare 'this' Klient with 'that' Klient and return true or false;
-
return ...;
-
}
Don't forget to implement the hashCode() method too. The two methods always
come in pairs, if you implement one you have to implement the other one too.
kind regards,
Jos
-
public boolean equals(Object o) {
-
if (!(o instanceof Klient)) return false;
-
Klient k = (Klient) o;
-
return nazwa ==k.nazwa && pieniadze == k.pieniadze;
-
}
-
i did it like this is it okey
-
public boolean equals(Object o) {
-
if (!(o instanceof Klient)) return false;
-
Klient k = (Klient) o;
-
return nazwa ==k.nazwa && pieniadze == k.pieniadze;
-
}
-
i did it like this is it okey
If 'nazwa' and 'pieniadze' can be compared for equality using the '==' operator,
I think all is fine. If one of them is an object (i.e. not a primitive) you have to
compare those members using the equals() method again (think about Strings).
Don't forget to implement the hashCode() method too.
kind regards,
Jos
but i have a problem here cos when one button is clicked i create a client and add it to the list then when other button is clicked that client adds to the cart but the client created with the first button is not seen in the other portion of the code (the code for the second button)
but i have a problem here cos when one button is clicked i create a client and add it to the list then when other button is clicked that client adds to the cart but the client created with the first button is not seen in the other portion of the code (the code for the second button)
That's an entirely different problem. Forget about GUIs for now and just take
care that your equals() and hashCode() methods are correctly implemented.
Build a little main() method that sticks Klients in a List and tries to find them
again afterwards. If all that works, build your GUI.
kind regards,
Jos
i wdnt have to add to the list if the equals method worked :)
i wdnt have to add to the list if the equals method worked :)
True, but my guess is that your equals() method doesn't work yet and the less
circumstancial code around (such as buttons etc.) the less difficult it is to
debug your code. Note that a list can store duplicate objects (the equals()
method returns true) so you should test before adding: -
if (!list.contains(klient)) list.add(klient);
... or you could use a Set for this but still then: your equals() method should
work correctly.
kind regards,
Jos
the equals method works i compared two clients
the equals method works i compared two clients
Good; did you override the hashCode() method too?
kind regards,
Jos
-
public int hashCode()
-
{
-
int result = 17;
-
result = 37 * result + pieniadze.hashCode();
-
result = 37 * result + nazwa.hashCode();
-
-
return result;
-
}
-
pieniadze is a double and i have a problem
and i dont know if it a good definition
-
public int hashCode()
-
{
-
int result = 17;
-
result = 37 * result + pieniadze.hashCode();
-
result = 37 * result + nazwa.hashCode();
-
-
return result;
-
}
-
pieniadze is a double and i have a problem
and i dont know if it a good definition
primitives don't have methods so 'double.hashCode()' doesn't make sense; but
why not simply cast the double value to an int and use that as the double's
hash value: -
int result = 17;
-
result = 37 * result + (int)pieniadze;
-
result = 37 * result + nazwa.hashCode();
Is 'nazwa' an object? If so you have to use its 'equals()' method in your own
'equals()' method (see a couple of replies back).
kind regards,
Jos
nazwa is a string and yes i used equals(nazwa.equals(k.nazwa)) in the equals method
but now what to do with the buttons problem
but now what to do with the buttons problem
I don't know; for starters: are both ActionListeners registered with those Buttons
using the same List? Add a lot of System.out.println(...) debug statements and
see what happens.
kind regards,
Jos
ps. does your equals() and hashCode() methods work correctly now?
thank u a lot lot lot yes they do :)
i did use lots of System.out.print() but the prob is that what's created by one button is not seen by the other button code and where to look 4 solution of that?
i did use lots of System.out.print() but the prob is that what's created by one button is not seen by the other button code and where to look 4 solution of that?
Are both ActionListeners using the same List in which you added your Klient
objects? Print out both lists everytime you access them and see what's in
them. (they both should be two references to one List).
kind regards,
Jos
ps. a List can print itself quite nicely because it overrides the toString() method.
i walked through the list and i know that the client is in that list but when i do
int index = klienci.indexOf(klient); it returns false
i walked through the list and i know that the client is in that list but when i do
int index = klienci.indexOf(klient); it returns false
Can't be, the indexOf() method returns an int; -1 possibly if no object was found.
I think you have to recheck your equals() method and your hashCode() method.
Print out what your equals() method has to say about every comparison.
kind regards,
Jos
that was with contains sorry so it returns -1
but
Klient k1 = new Klient("Jan",200);
Klient k2 = new Klient ("Jan",200);
System.out.print(k1.equals(k2));
returns true
int index = klienci.indexOf(klient);
if(index != -1) {
klient = klienci.get(index);
}
else {
// 'klient' is not in the list 'klienci'
}
that was with contains sorry so it returns -1
but
Klient k1 = new Klient("Jan",200);
Klient k2 = new Klient ("Jan",200);
System.out.print(k1.equals(k2));
returns true
int index = klienci.indexOf(klient);
if(index != -1) {
klient = klienci.get(index);
}
else {
// 'klient' is not in the list 'klienci'
}
You did do a 'klienci.add(k1)' or 'klienci.add(k2)' did you? If so, can you show
your equals method just to be sure? Add a System.out.println() to your equals()
method to see if it is called by your List.
kind regards,
Jos
public boolean equals(Object o) {
if (!(o instanceof Klient)) return false;
Klient k = (Klient) o;
return nazwa.equals(k.nazwa) && pieniadze == k.pieniadze;
}
i will show u how it is with the buttons -
m_add_client.addActionListener( new ActionListener() {
-
public void actionPerformed(ActionEvent e) {
-
-
try{
-
-
//Klient k = new Klient((String)m_name.getText(),Double.valueOf(m_money.getText().trim()).doubleValue());
-
-
-
klienci.add(new Klient((String)m_name.getText(),Double.valueOf(m_money.getText().trim()).doubleValue()));
-
-
}catch(NumberFormatException exception){
-
System.err.println("Nie podana suma pieniedzy");
-
}
-
catch(NullPointerException exception){
-
System.err.println("?");
-
}
-
}
-
});
then the other button -
m_add.addActionListener( new ActionListener() {
-
public void actionPerformed(ActionEvent e) {
-
-
try{
-
Cennik c= Cennik.getInstance();
-
Klient klient = new Klient((String)m_name.getText(),Double.valueOf(m_money.getText().trim()).doubleValue());
-
-
-
-
-
-
-
-
//if(k.equals(klient)) {klient=k;} // k is not seen here but that wd solve my problem i wd only compare the two client objects
-
-
//but i have to find a client in a list
-
int index = klienci.indexOf(klient);
-
-
if(index != -1) {
-
klient = klienci.get(index);
-
-
}
-
else {
-
// 'klient' is not in the list 'klienci'
-
}
-
-
and the rest of the code
-
BTW Happy Easter
Happy Easter to you too and to everybody else reading this.
About your equals() method: it seems ok (as well as the rest of your code)
except for one thing: you're comparing two double values; two double values
are almost never equal to each other. Can you add some System.out.println()
methods in your equals() method showing exactly *what* is compared to *what*.
Also print out what the equals() method wants to return. To be sure remove those
doubles from your hashCode() method, i.e. return the hashCode() if those Strings
only.
I think you're almost there. ;-)
kind regards,
Jos
but first i have the equals method but where in the code is place for that method if i already have a list and i can get the object with klient = klienci.get(index);
also two doubles that may be the reason why int index = klienci.indexOf(klient); returns -1
but first i have the equals method but where in the code is place for that method if i already have a list and i can get the object with klient = klienci.get(index);
also two doubles that may be the reason why int index = klienci.indexOf(klient); returns -1
Good morning; you could (and should) put these System.out.println() statements
in your own equals() method, i.e. print the values of the two objects to be
compared as well as the boolean that is to be returned to the caller. The List
is the caller of course and you can't change anything in the List code itself.
kind regards,
Jos
Good Morning :) -
public boolean equals(Object o) {
-
if (!(o instanceof Klient)) return false;
-
Klient k = (Klient) o;
-
System.out.println(nazwa);
-
System.out.println(k.nazwa);
-
System.out.println(pieniadze);
-
System.out.println(k.pieniadze);
-
return nazwa.equals(k.nazwa) && pieniadze == k.pieniadze;
-
}
-
-
public static void main(String[] args) {
-
-
Klient k1 = new Klient("Jan",200);
-
Klient k2 = new Klient ("Jan",200);
-
-
System.out.print(k1.equals(k2));
-
}
-
}
-
-
prints out
Jan
Jan
200.0
200.0
true
is that what you meant
Good Morning :)
is that what you meant
Yep, what happens now if you use the List.contains(...) method after you've
inserted one of those Klients? The List should call your equals() method for
the actual comparisons (which in turn show you what actually is compared).
kind regards,
Jos
now it finds a client in a list
...but i get nullpointerexception :( and eclipse doesnt say the line
now it finds a client in a list
...but i get nullpointerexception :( and eclipse doesnt say the line
Do you have a 'null' element in your List? Print the entire list (a List can do
it itself): -
System.out.println(yourList);
... and see for yourself.
kind regards,
Jos
the client is in a list the nullointerexception is somewhere else but after i click a button
Sign in to post your reply or Sign up for a free account.
Similar topics
by: lawrence |
last post by:
How dangerous or stupid is it for an object to have a reference to the
object which contains it? If I have a class called $controllerForAll
which has an arrray of all the objects that exist, what...
|
by: Jonathan |
last post by:
I am looking for a simple way to check if a database table exists. I
keep getting advice to use "Try.. Catch" and other error handling
methods, but I obviously don't want to have to display an...
|
by: Mike |
last post by:
I´ve got a number of SPAN elements named "mySpan1", "mySpan2", "mySpan3"
etc, and want to set their "style.display" to "inline".
This works (only needs to work on IE5.5+):
for (var x = 1; x <...
|
by: Carl Fenley |
last post by:
I am successfully adding stored procedures to an Access database. However,
I need to be able to check if the stored procedure of the same name already
exists.
Is there a way to do this other...
|
by: jes |
last post by:
hi,
i have an open & delete btn. onclick of open as visio drawing opens in visio
& onclick of delete the drawing gets deleted from the filesystem. The problem
is i am unable to perform these...
|
by: John Salerno |
last post by:
What is the best way to check if a file already exists in the current
directory? I saw os.path.isfile(), but I'm not sure if that does more
than what I need.
I just want to check if a file of a...
|
by: byeung |
last post by:
Hi,
I am trying to check if a particular record already exists in an Access
database through Excel vba code. Through code obtained at another
forum, I got the following:
...
|
by: Larry |
last post by:
Thanks in advance.
what is the C# equivalent of the VB.net IsNothing(object) function?
just trying to check to see if an object instance already exists.
does someone have an example?
*** Sent...
|
by: bharathreddy |
last post by:
This article will explain you how to check weather a column already exists in a table before you add the column to the table using alter command.
Using the system tables...
|
by: taylorcarr |
last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: ryjfgjl |
last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
| |