Get position of element from hashset

Following on from a previous question, I have something else which I am unable to find conventially.

I have a hashset (trains) which is filled with elements. I'd like to write something which gets the position of that element in the hashset based on a string I pass to it.

I have something similar for hashtables which was taken from a question which someone else asked before
      public static int getKey(String Station)
      {
            int counter=0;
            int place  =0;
            int keyLocation = 0;

            for (Enumeration i=stations.elements(); i.hasMoreElements();)
            {
            counter++;
                  if( i.nextElement().equals(Station))
                  {
                        for (Enumeration j=stations.keys() ; j.hasMoreElements();)
                        {
                              place++;
                              if( counter == place)
                              {
                                    keyLocation =((Integer)j.nextElement());
                              }
                              else
                              j.nextElement();    
                        }
                  }
            }
            return keyLocation;
      }


From this, I'd like to be able to return the integer of the element in the hashset.

If this cannot be done, then I would like to know (like my previous question) if it's possible to create a hashtable outside a method (as in, just inside the class) so that it can be referenced.

Thankyou in advance.
DanBAtkinsonAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

CEHJCommented:
>>I'd like to write something which gets the position of that element in the hashset

Why do you want it? As i mentioned in your previous, Set is inherently *un*ordered.
CEHJCommented:
>>Set is inherently *un*ordered.

(Unless it's LinkedHashSet) Even then, although backed by a List it's not indexable. You would probably be better to turn it into a List, which *is* ordered

List x = new ArrayList(yourSet);

DanBAtkinsonAuthor Commented:
CEHJ:
  Yes :-). Thankyou, you're right of course!
  Ok then, is it possible to create a hashtable inside the class which can be referenced?

I have something along the lines of this in mind:

public static Hashtable trains()
{
    trains.put(1, "Walthamstow Central");
    trains.put(2, "Blackhorse Road");
    ...
}

And then this could be referenced using the getKey as mentioned before.
OWASP Proactive Controls

Learn the most important control and control categories that every architect and developer should include in their projects.

DanBAtkinsonAuthor Commented:
That comment was referring to your first post!
Mick BarryJava DeveloperCommented:
Use a LinkedHashSet

http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedHashSet.html

Or maintain a seperate list, adding elements to the list if they don't already exist in the Set (use its contains() method
DanBAtkinsonAuthor Commented:
CEHJ: Thanks. In the context of creating a list, how would this be implemented so that it could be searchable in a similar way to the hashtable?
CEHJCommented:
>>I'd like to be able to return the integer of the element in the hashset.

If you used a List (per my code above) all you'd need to do is:

int index = list.indexOf("Walthamstow Central");
DanBAtkinsonAuthor Commented:
objects: I need to get the position/index of the array/hash* to use it further in other parts of the program and I can't see anything for LinkedHashSet which allows me to get that.
Mick BarryJava DeveloperCommented:
I see then maintaina seperate list

when you add an item to the set also add it to list (if not in set)

if (!set.contains(station))
{
   list.add(station);
   set.add(station);
}
DanBAtkinsonAuthor Commented:
CEHJ: Sorry. You misunderstood me because I didn't ask the question correctly. :(

I meant how would I create this in the first place so that I can reference it later (ie outisde methods/functions etc)?

My attempts at creating tables like this have had problems which led me to ask the last question.
Mick BarryJava DeveloperCommented:
you could do away with the set altogether if you wanted as ArrayList also has a contains() method.
But using the set would still be a little more effiecient, though in your case its no big deal.

f (!list.contains(station))
{
   list.add(station);
}
DanBAtkinsonAuthor Commented:
objects: How would I create something like this in the class so that it can be referenced by other functions and the actual program?
Mick BarryJava DeveloperCommented:
You could return the list from the method as you are already doing.
Or make the list a member variable instead of a local one
CEHJCommented:
>>I meant how would I create this in the first place so

Well you could keep an instance variable of type List and then initialize it when you're ready in a method:

private List stationList;

...



private List getStationList(Set stationSet) {
    if (stationList == null) {
        stationList = new ArrayList(stationSet);
    }
    return stationList;
}

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
DanBAtkinsonAuthor Commented:
So something like?:

      private static List stationList;

      private static List getStationList(Set stationSet)
      {
            if (stationList == null)
            {
                  stationList = new ArrayList(stationSet);
                  stationList.add("Walthamstow Central");
                  stationList.add("Blackhorse Road");
                  ...
                  ...
            }
            return stationList;
      }



Later on...

      public static int getIndex(String Station)
      {
            return stationList.indexof(Station);
      }

?
CEHJCommented:
Yes, but of course, since you seem to have a Set, you can simply pass it into that method
DanBAtkinsonAuthor Commented:
Thanks! There's something wrong though...

I get the following error for this:

cannot find symbol
symbol  : method indexof(java.lang.String)
location: interface java.util.List
            return stationList.indexof(Station);
                                 ^

Any ideas?
Mick BarryJava DeveloperCommented:
> So something like?:

you just need to replace your existing code with this:

List getStations()
{
     List interchanges = new ArrayList();
     for (int i=0;i<stationInterchange.length;i++)
     {
          String[] inter = stationInterchange[i].split(",");
          for (int j=0; j<inter.length; j++)
          {
              if (!interchanges.contains(inter[j]))
              {
                    interchanges.add(inter[j]);
               }
          }
     }
     return interchanges;
}
Mick BarryJava DeveloperCommented:
>           return stationList.indexof(Station);

shopuld be:

          return stationList.indexOf(Station);
DanBAtkinsonAuthor Commented:
I feel a little bit silly about the indexOf?! :( Having fixed that, I get another error when running...

The search method only returns a nullPointerException.
DanBAtkinsonAuthor Commented:
objects: This is slightly different from what I'm doing with the interchange work.
Mick BarryJava DeveloperCommented:
What I'm saying is that you should be storing it in a list in the first place, and not using a set at all.
If you need an indexed collection then a list is appropriate, not a set.
DanBAtkinsonAuthor Commented:
How would that be implimented?

I'm not sure how to do it. :(
DanBAtkinsonAuthor Commented:
     private static List stationList;

      public static List getStations()
      {
                  stationList = new ArrayList();
                  stationList.add("Walthamstow Central");
                  ...
                  ...
                  return stationList;
      }


Later:::


public static int getIndex(String Station)
{
      return stationList.indexOf(Station);
}
DanBAtkinsonAuthor Commented:
I'm not sure if this is what you mean but I get the same java.lang.NullPointerException error either way.
Mick BarryJava DeveloperCommented:
> How would that be implimented?
> I'm not sure how to do it. :(

how do u currently create your set?
you would change that to instead create a list, checking whether each item was already in the list before adding it

> I'm not sure if this is what you mean but I get the same java.lang.NullPointerException error either way.

sounds like you don't call getStations()
DanBAtkinsonAuthor Commented:
objects:

The set is created as shown above:

      private static List stationList;

      public static List getStations()
      {
                  stationList = new ArrayList();
                  stationList.add("Walthamstow Central");
                  stationList.add("Blackhorse Road");
                  
                  return stationList;
      }


And is accessed with:

      public static int getIndex(String Station)
      {
            return stationList.indexOf(Station);
      }
DanBAtkinsonAuthor Commented:
I've re-written the getIndex accordingly.

      public static int getIndex(String Station)
      {
            return getStations().indexOf(Station);
      }
DanBAtkinsonAuthor Commented:
That works now!

Thanks very much. I'm going to leave it at this because it's 02:25 in the morning.

Points awarded to objects and an assist to CEHJ (250:250). An even split because CEHJ provided the initial code but objects expanded on it (and provided other ideas) and gave support on the problems.

Once again, thankyou very much!

You've been very helpful! Hopefully I can go back to making pretty stylesheets and pretend that Java doesn't exist! :)
Mick BarryJava DeveloperCommented:
> The set is created as shown above:

where, I can't see any code that creates a set

>           return getStations().indexOf(Station);

if you're doing that then change getStations() to:

     public static List getStations()
     {
               if (stationList==null) {
                 stationList = new ArrayList();
                 stationList.add("Walthamstow Central");
                  stationList.add("Blackhorse Road");
               }
               return stationList;
     }
DanBAtkinsonAuthor Commented:
Set? No. Sorry. No set is created. Just the list.
DanBAtkinsonAuthor Commented:
And the getStations() has been re-written like that.

Thanks.
CEHJCommented:
:-)
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.