We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you a podcast all about Citrix Workspace, moving to the cloud, and analytics & intelligence. Episode 2 coming soon!Listen Now

x

Get position of element from hashset

DanBAtkinson
DanBAtkinson asked
on
Medium Priority
708 Views
Last Modified: 2010-03-31
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.
Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2016

Commented:
>>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.
CERTIFIED EXPERT
Top Expert 2016
Commented:
>>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);

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

Author

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.

Author

Commented:
That comment was referring to your first post!
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
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

Author

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?
CERTIFIED EXPERT
Top Expert 2016

Commented:
>>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");

Author

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 Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
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);
}

Author

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 Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
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);
}

Author

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 Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
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
CERTIFIED EXPERT
Top Expert 2016
Commented:
>>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;
}

Author

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);
      }

?
CERTIFIED EXPERT
Top Expert 2016

Commented:
Yes, but of course, since you seem to have a Set, you can simply pass it into that method

Author

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 Developer
CERTIFIED EXPERT
Top Expert 2010
Commented:
> 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 Developer
CERTIFIED EXPERT
Top Expert 2010
Commented:
>           return stationList.indexof(Station);

shopuld be:

          return stationList.indexOf(Station);

Author

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.

Author

Commented:
objects: This is slightly different from what I'm doing with the interchange work.
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
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.

Author

Commented:
How would that be implimented?

I'm not sure how to do it. :(

Author

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);
}

Author

Commented:
I'm not sure if this is what you mean but I get the same java.lang.NullPointerException error either way.
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
> 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()

Author

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);
      }

Author

Commented:
I've re-written the getIndex accordingly.

      public static int getIndex(String Station)
      {
            return getStations().indexOf(Station);
      }

Author

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 Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
> 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;
     }

Author

Commented:
Set? No. Sorry. No set is created. Just the list.

Author

Commented:
And the getStations() has been re-written like that.

Thanks.
CERTIFIED EXPERT
Top Expert 2016

Commented:
:-)
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.