How do I throw and UnsupportedOperationException on a method? So if I have an Iterable object and I'm trying to disallow the remove method for that object.

In the method below I'm returning an iterable object whose iterator's remove I need to disable by throwing an UnsupportedErrorException. Can I do this within the body of the method or how so?

  public Iterable<String> getInNodes (String destinationNodeName)  {
  if (!hasNode(destinationNodeName))
      return emptySetOfString;
  else {
  for(String e : nodeMap.get(destinationNodeName).inNodes)
  {
      emptySetOfString.add(e);
  }
  return emptySetOfString;
  }
}
有帮助吗?

解决方案

Try this.

@Override
public void remove() {
   throw new UnsupportedOperationException();
}

其他提示

I may have misunderstood your question.

If you have a normal Iterable, and you want to convert it to an Iterable that generates iterators on which remove can not be called, you can use this monstrosity made possible by anonymous subclassing:

Iterable<String> iterable = // normal Iterable<String> you already have...

Iterable<String> noRemoveIteratorGeneratingIterable = new Iterable<String>() {
    @Override        
    public Iterator<String> iterator() {
        return new Iterator<String>() {
            Iterator<String> internalIterator = iterable.iterator();

            @Override
            public boolean hasNext() {
                return internalIterator.hasNext();
            }

            @Override
            public String next() {
                return internalIterator.next();
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException("Nope!");
            }
        };
    }
};

In your class you can just @Override the original method

public class myIterable extends Iterable {
    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }
}

Then create Objects of this class instead of original Iterable.

You can try throwing the message with appropriate message as well:

public void remove() {
   throw new UnsupportedOperationException("Remove is unsupported on this object");
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top