shine <su***********@ gmail.com> wrote:
I am trying to add an integer array to a hashtable.
While adding to hashtable I want to check the duplicates in array, the
way I want to do is add the key(the integer stored in array) if a
duplicate key is being added then the program should return the integer
else it should return -1.
Here is the piece of code I have written does the logic looks ok ?
------------------------------------------------------------------
class SearchDuplicate Entry {
int[] ArrayOfInt = new int(N);
int Length = ArrayOfInt.leng th;
int Count = 0;
Hashtable h = new hashtable();
try
{
for(int i=0; i<Length; i++)
{
Count++;
h.Add(ArrayOfIn t[i],Count);
}
}
catch(Exception e)
{
Console.Writeli ne("ArrayofInt[i]");
}
return -1;
}
I want to know if I am thinking in right direction.
Any help will be greatly appreciated, thanks so much.
Okay, problems with the above:
1) You need code to be in a method, not just directly in the class
body.
2) Most people don't use camel case for parameters and local variables
- use it for properties, method names and type names.
3) C# is case sensitive - you need new Hashtable(), not new
hashtable(). (It's always worth posting code which actually works if
possible.)
4) Why do you have the local variable "Length"? Why not just do
for (int i=0; i < ArrayOfInt.Leng th; i++)
{
....
}
or even better
foreach (int i in ArrayOfInt)
{
....
}
5) You shouldn't be catching an exception here - what are you expecting
to go wrong, and why do you think you shouldn't let that exception
propagate?
6) It's not at all clear what the "bigger picture" is here - are you
*just* trying to find duplicates, and just the first duplicate at that?
If so, I wouldn't bother putting the value as "count" - I don't see any
benefit. Just test using Hashtable.Conta insKey before adding the key
(returning the key if it's already present instead) and then set the
value for the key to be null (or some other constant reference -
there's no point in boxing something you're not going to use again).
--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too