Home > other >  How do you convert an arrayStack of Object into HashSet?
How do you convert an arrayStack of Object into HashSet?

Time:03-11

        public Set<Cell> solve(Maze maze) {

          ArrayStack<Cell> path = new ArrayStack<Cell>()

          return (Set<Cell>) path;

I'll keep it short, but I have made my maze solver and it works and it's stored in ArrayStack 'path' and I'm trying to convert it to a Set so I can return it but it isn't working and it's saying 'Unchecked cast'. Any suggestion on how I could fix this?

I tried iterating,

 HashSet<Cell> test = new HashSet<>();
    while(!path.isEmpty()) {
        marker.add(path.pop());
    }

    Iterator<Cell> itr = test.iterator();
    while(itr.hasNext()) {
        System.out.println(itr.next());
    }

It's not really showing how I wanted it to be even if it's reversed.

CodePudding user response:

If it is org.apache.commons.collections.ArrayStack, you can create the set with

return new HashSet<>(path);

Please note that a set can contain each object only once and the order of objects is not guaranteed. The "contain only once" is checked with .equals() (and .hashcode()) of the contained objects (so you might want to override those methods with a proper implementation for Cell).

CodePudding user response:

Assuming you are using the Apache ArrayStack class...

ArrayStack does not implement the Set interface so you cannot cast it to that type.

You need to create an instance of a Set implementation and populate it with the elements from the ArrayStack. Note that the Set interface is specifically un-ordered. If you want Set semantics but in a reliable order then consider using a TreeSet rather than a HashSet. TreeSet implements SortedSet and will produce its elements in their natural ordering when iterated. Since ArrayStack implements Collection, you should be able to do the following:

return new TreeSet<Cell>(path);

This assumes that Cell has a natural ordering that matches the position within the path.

  •  Tags:  
  • java
  • Related