473,385 Members | 1,893 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

how to check if an object already exists

oll3i
679 512MB
how to check if an object already exists and return reference to that object
Apr 5 '07 #1
59 32626
RedSon
5,000 Expert 4TB
Can you please describe your question in more detail?
Apr 5 '07 #2
oll3i
679 512MB
i have to write a flower shop
i need to check if a client already exists so that i dont add a new one
Apr 6 '07 #3
hirak1984
316 100+
[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
Apr 6 '07 #4
prometheuzz
197 Expert 100+
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?
Apr 6 '07 #5
oll3i
679 512MB
in a list of clients
Apr 6 '07 #6
JosAH
11,448 Expert 8TB
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.
Apr 6 '07 #7
oll3i
679 512MB
[code]
if(klienci.contains(klient)){
int index=klienci.indexOf(klient);

klient=klienci.get(index);
}

[code]

but it doesnt find the client in the list
Apr 7 '07 #8
hirak1984
316 100+
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
Apr 7 '07 #9
prometheuzz
197 Expert 100+
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:
Expand|Select|Wrap|Line Numbers
  1. int index = klienci.indexOf(klient);
  2.  
  3. if(index != -1) {
  4.   klient = klienci.get(index);
  5. else {
  6.   // 'klient' is not in the list 'klienci'
  7. }
Apr 7 '07 #10
oll3i
679 512MB
i get nullpointerexception
Apr 7 '07 #11
oll3i
679 512MB
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
Apr 7 '07 #12
JosAH
11,448 Expert 8TB
Does your Klient class override the equals() and hashCode() methods?

kind regards,

Jos
Apr 7 '07 #13
oll3i
679 512MB
no it doesnt shd it?
Apr 7 '07 #14
JosAH
11,448 Expert 8TB
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
Apr 7 '07 #15
oll3i
679 512MB
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
Apr 7 '07 #16
hirak1984
316 100+
can I see how you have defined the object variable?

Did you set it to null , initially?

i get nullpointerexception
Apr 7 '07 #17
JosAH
11,448 Expert 8TB
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)
Expand|Select|Wrap|Line Numbers
  1.     public boolean contains(Object o) {
  2.     Iterator<E> e = iterator();
  3.     if (o==null) {
  4.         while (e.hasNext())
  5.         if (e.next()==null)
  6.             return true;
  7.     } else {
  8.         while (e.hasNext())
  9.         if (o.equals(e.next()))
  10.             return true;
  11.     }
  12.     return false;
  13.     }
See how it uses the equals() method when it needs to find an object.

kind regards,

Jos
Apr 7 '07 #18
oll3i
679 512MB
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
Apr 7 '07 #19
JosAH
11,448 Expert 8TB
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:
Expand|Select|Wrap|Line Numbers
  1. public class Klient {
  2.    .
  3.    .
  4.    public boolean equals(Object obj) {
  5.       if (obj == null || !(obj instanceof Klient)) return false;
  6.       Klient that= (Klient)obj;
  7.       // compare 'this' Klient with 'that' Klient and return true or false;
  8.       return ...;
  9.    }
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
Apr 7 '07 #20
oll3i
679 512MB
Expand|Select|Wrap|Line Numbers
  1. public boolean equals(Object o) {
  2.     if (!(o instanceof Klient)) return false;
  3.     Klient k = (Klient) o;
  4.     return  nazwa ==k.nazwa && pieniadze == k.pieniadze;
  5.   }
  6.  
i did it like this is it okey
Apr 7 '07 #21
JosAH
11,448 Expert 8TB
Expand|Select|Wrap|Line Numbers
  1. public boolean equals(Object o) {
  2.     if (!(o instanceof Klient)) return false;
  3.     Klient k = (Klient) o;
  4.     return  nazwa ==k.nazwa && pieniadze == k.pieniadze;
  5.   }
  6.  
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
Apr 7 '07 #22
oll3i
679 512MB
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)
Apr 7 '07 #23
JosAH
11,448 Expert 8TB
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
Apr 7 '07 #24
oll3i
679 512MB
i wdnt have to add to the list if the equals method worked :)
Apr 7 '07 #25
JosAH
11,448 Expert 8TB
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:
Expand|Select|Wrap|Line Numbers
  1. 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
Apr 7 '07 #26
oll3i
679 512MB
the equals method works i compared two clients
Apr 7 '07 #27
JosAH
11,448 Expert 8TB
the equals method works i compared two clients
Good; did you override the hashCode() method too?

kind regards,

Jos
Apr 7 '07 #28
oll3i
679 512MB
Expand|Select|Wrap|Line Numbers
  1. public int hashCode()
  2. {
  3. int result = 17;
  4. result = 37 * result + pieniadze.hashCode();
  5. result = 37 * result + nazwa.hashCode();
  6.  
  7. return result;
  8. }
  9.  
pieniadze is a double and i have a problem
and i dont know if it a good definition
Apr 7 '07 #29
JosAH
11,448 Expert 8TB
Expand|Select|Wrap|Line Numbers
  1. public int hashCode()
  2. {
  3. int result = 17;
  4. result = 37 * result + pieniadze.hashCode();
  5. result = 37 * result + nazwa.hashCode();
  6.  
  7. return result;
  8. }
  9.  
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:
Expand|Select|Wrap|Line Numbers
  1. int result = 17;
  2. result = 37 * result + (int)pieniadze;
  3. 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
Apr 7 '07 #30
oll3i
679 512MB
nazwa is a string and yes i used equals(nazwa.equals(k.nazwa)) in the equals method
Apr 7 '07 #31
oll3i
679 512MB
but now what to do with the buttons problem
Apr 7 '07 #32
JosAH
11,448 Expert 8TB
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?
Apr 7 '07 #33
oll3i
679 512MB
thank u a lot lot lot yes they do :)
Apr 7 '07 #34
oll3i
679 512MB
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?
Apr 7 '07 #35
JosAH
11,448 Expert 8TB
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.
Apr 7 '07 #36
oll3i
679 512MB
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
Apr 7 '07 #37
JosAH
11,448 Expert 8TB
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
Apr 7 '07 #38
oll3i
679 512MB
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'
}
Apr 7 '07 #39
JosAH
11,448 Expert 8TB
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
Apr 7 '07 #40
oll3i
679 512MB
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

Expand|Select|Wrap|Line Numbers
  1. m_add_client.addActionListener( new ActionListener() {
  2.                     public void actionPerformed(ActionEvent e) {
  3.  
  4. try{
  5.  
  6.  //Klient k = new Klient((String)m_name.getText(),Double.valueOf(m_money.getText().trim()).doubleValue()); 
  7.  
  8.  
  9. klienci.add(new Klient((String)m_name.getText(),Double.valueOf(m_money.getText().trim()).doubleValue()));                       
  10.  
  11. }catch(NumberFormatException exception){
  12. System.err.println("Nie podana suma pieniedzy");
  13. }  
  14. catch(NullPointerException exception){
  15. System.err.println("?");
  16. }
  17. }
  18. });

then the other button

Expand|Select|Wrap|Line Numbers
  1.  m_add.addActionListener( new ActionListener() {
  2.                     public void actionPerformed(ActionEvent e) {
  3.  
  4.                         try{
  5.                         Cennik c= Cennik.getInstance();
  6.                         Klient klient = new Klient((String)m_name.getText(),Double.valueOf(m_money.getText().trim()).doubleValue()); 
  7.  
  8.  
  9.  
  10.  
  11.  
  12.  
  13.  
  14. //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 
  15.  
  16. //but i have to find a client in a list 
  17.                        int index = klienci.indexOf(klient);        
  18.  
  19.                         if(index != -1) {
  20.                           klient = klienci.get(index);
  21.  
  22.                         } 
  23.                         else {
  24.                           // 'klient' is not in the list 'klienci'
  25.                         }
  26.  
  27.                       and the rest of the code
  28.  
Apr 7 '07 #41
oll3i
679 512MB
BTW Happy Easter
Apr 7 '07 #42
JosAH
11,448 Expert 8TB
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
Apr 7 '07 #43
oll3i
679 512MB
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
Apr 7 '07 #44
JosAH
11,448 Expert 8TB
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
Apr 8 '07 #45
oll3i
679 512MB
Good Morning :)
Expand|Select|Wrap|Line Numbers
  1. public boolean equals(Object o) {
  2.     if (!(o instanceof Klient)) return false;
  3.     Klient k = (Klient) o;
  4.     System.out.println(nazwa);
  5.     System.out.println(k.nazwa);
  6.     System.out.println(pieniadze);
  7.     System.out.println(k.pieniadze);
  8.     return  nazwa.equals(k.nazwa) && pieniadze == k.pieniadze;
  9.   }
  10.  
  11. public static void main(String[] args) {
  12.  
  13.     Klient k1 = new Klient("Jan",200);
  14.     Klient k2 = new Klient ("Jan",200);
  15.  
  16.     System.out.print(k1.equals(k2));
  17. }
  18. }
  19.  
  20.  
prints out
Jan
Jan
200.0
200.0
true

is that what you meant
Apr 8 '07 #46
JosAH
11,448 Expert 8TB
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
Apr 8 '07 #47
oll3i
679 512MB
now it finds a client in a list

...but i get nullpointerexception :( and eclipse doesnt say the line
Apr 8 '07 #48
JosAH
11,448 Expert 8TB
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):
Expand|Select|Wrap|Line Numbers
  1. System.out.println(yourList);
... and see for yourself.

kind regards,

Jos
Apr 8 '07 #49
oll3i
679 512MB
the client is in a list the nullointerexception is somewhere else but after i click a button
Apr 8 '07 #50

Sign in to post your reply or Sign up for a free account.

Similar topics

6
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...
2
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...
2
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 <...
9
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...
4
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...
14
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...
3
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: ...
2
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...
0
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...
0
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,...
0
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$) { } ...
0
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...
0
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
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...
0
marktang
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,...
0
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...
0
jinu1996
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...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.