• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 635
  • Last Modified:

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.
0
DanBAtkinson
Asked:
DanBAtkinson
  • 18
  • 9
  • 6
4 Solutions
 
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.
0
 
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);

0
 
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.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
DanBAtkinsonAuthor Commented:
That comment was referring to your first post!
0
 
objectsCommented:
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
0
 
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?
0
 
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");
0
 
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.
0
 
objectsCommented:
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);
}
0
 
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.
0
 
objectsCommented:
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);
}
0
 
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?
0
 
objectsCommented:
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
0
 
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;
}
0
 
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);
      }

?
0
 
CEHJCommented:
Yes, but of course, since you seem to have a Set, you can simply pass it into that method
0
 
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?
0
 
objectsCommented:
> 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;
}
0
 
objectsCommented:
>           return stationList.indexof(Station);

shopuld be:

          return stationList.indexOf(Station);
0
 
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.
0
 
DanBAtkinsonAuthor Commented:
objects: This is slightly different from what I'm doing with the interchange work.
0
 
objectsCommented:
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.
0
 
DanBAtkinsonAuthor Commented:
How would that be implimented?

I'm not sure how to do it. :(
0
 
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);
}
0
 
DanBAtkinsonAuthor Commented:
I'm not sure if this is what you mean but I get the same java.lang.NullPointerException error either way.
0
 
objectsCommented:
> 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()
0
 
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);
      }
0
 
DanBAtkinsonAuthor Commented:
I've re-written the getIndex accordingly.

      public static int getIndex(String Station)
      {
            return getStations().indexOf(Station);
      }
0
 
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! :)
0
 
objectsCommented:
> 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;
     }
0
 
DanBAtkinsonAuthor Commented:
Set? No. Sorry. No set is created. Just the list.
0
 
DanBAtkinsonAuthor Commented:
And the getStations() has been re-written like that.

Thanks.
0
 
CEHJCommented:
:-)
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 18
  • 9
  • 6
Tackle projects and never again get stuck behind a technical roadblock.
Join Now