3

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; } } 
1
  • 2
    throw new UnsupportedOperationException() ? Commented Dec 5, 2012 at 3:09

4 Answers 4

5

Try this.

@Override public void remove() { throw new UnsupportedOperationException(); } 
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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.

Comments

0

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

public void remove() { throw new UnsupportedOperationException("Remove is unsupported on this object"); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.