I have to order a list by the name attribute of the objects it contains, but what I have done gives me an error. this is my method
public static List consultarPropietarios(ObjectContainer db) {
Propietario propietario = new Propietario(null, null, null, null, null, null, null);
ObjectSet res = db.queryByExample(propietario);
List<Propietario> a = res;
Comparator<Propietario> compareByNom = (Propietario p1, Propietario p2) -> p1.getNombre().compareToIgnoreCase(p2.getNombre());
Collections.sort(a, compareByNom);
return a;
}
This is the error it gives
Exception in thread "AWT-EventQueue-0" java.lang.UnsupportedOperationException
at java.util.AbstractList.set(AbstractList.java:132)
at java.util.AbstractList$ListItr.set(AbstractList.java:426)
at java.util.List.sort(List.java:482)
If I'm not mistaken, you're using ObjectSet, which is an interface to the db4o library (which is deprecated, not supported).
This interface extends List, which has a method
sort
. The spec says that this method will throw an exceptionUnsupportedOperationException
if it is not implemented (for example, if the list is immutable).On the other hand, we have the method
Collections.sort(List<T> list, Comparator<? super T> c)
, which allows sorting lists without using their sort method. But it has a requirement: to be able to sort a list you need the methodList.set(int index, E element)
to be able to put each element in its place. Again, if the list does not have this method implemented because it is immutable an exception will be thrownUnsupportedOperationException
.So the problem you have is that the class that uses your library and implements ObjectSet is not modifiable.
You have two simple solutions:
ORDER BY <campo> DESC|ASC
" to the query.Final note:
Casting doesn't do magic : You're telling the compiler that a certain instance is of class X, but if it isn't, you're just tricking it. You can't create a class that implements List and then cast ArrayList thinking that you automatically have ArrayList's methods available.
It is the equivalent of lying on a CV: if for example you say you speak Chinese, they will believe you as long as you don't have to speak it, but the moment someone asks you to translate something, the cake will be revealed ( ClassCastException , it is not a ChineseSpanish Translator ) ; )