UnsupportedOperationException while removing element from List


 i have a List<File> queryPool;

 in findImage() method, I loop thru the queryPool and find one image called queryImage of type File, which i return to main function

 and while trying to remove this from the queryPool -


it throws the java.lang.UnsupportedOperationException .. i tried using Iterator over the queryPool, still error

any comments?
protected File findImage() {
 // some calculations
 for(File f : queryPool) {
   // calculations
   if(closeValues.get(f) < temp2) {
	queryImage = f;
return queryImage;

Open in new window

Who is Participating?
If you want to remove it while iterating, you should

a. clone the File to return to the caller
b. Use Iterator explicitly and call remove on it
once you have created an iterator for a collection you should explicitly use the add and remove methods from the iterator. if you try to add or remove from the collection directly you will get the exception.
max_dubAuthor Commented:
"explicitly use the add and remove methods" - can u explain this bit
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

check your list implementation,
if you are trying to get the list using Arrays.asList(), then the returned list do not support
the remove,

since it is java.util.Arrays$ArrayList and not java.util.ArrayList
chekc the class with list.getClass()
if you use an iterator and try to remove the object from the list, it should throw a ConcurrentModificationException and not UnSuportedOperationExcepotion,

UnSupported..Exception is thrown by the remove() method in the AbstractList(), if the implementation of this class do no impleemnt remove() then u will get that exception

This is the sort of thing you need to do
        List<File> fileList = new ArrayList(Arrays.asList(new File(".").listFiles()));
        Iterator<File> i = fileList.iterator();
        String copied = null;
        while (i.hasNext()) {
            File f = i.next();
            if (f.getName().equals("b")) {
                copied = f.getName();

Open in new window

max_dubAuthor Commented:
thanks guys..

i was missing the remove function from the List implementation from an external jar i was using.. i added the remove function there n it works

max_dubAuthor Commented:
ah, sorry i wanted the CEHJ answer to be assisted solution, but it turned out other way around .. always .. thanks mukundha_expert for ur solution
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.