Java 6 Collections.checkedList appropriate usage - java

I am creating several functions in which I want to return the interface instead of the implementation, I.E. List instead of ArrayList . My method signature and a brief implementation follows:
public List<MyAwesomeComposedObject> convert(Collection<MyAwesomeObject> awesomeObjects>)
{
List<MyAwesomeComposedObject> composedObjects = new ArrayList<MyAwesomeComposedObject>();
for(MyAwesomeObject awesomeObject : awesomeObjects)
{
MyAwesomeComposedObject composedObject = new MyAwesomeComposedObject(awesomeObject);
composedObjects.add(composedObject);
}
List<MyAwesomeComposedObject> composedObjectList = Collections.checkedList<composedObjects, MyAwesomeComposedObject.class);
return composedObjectList;
}
My question is, is this an antipattern of some sort? I want to guarantee that the invoker of this method is getting the interface instead of an implementation. I also do not believe this to be a case of overengineering. If this is not the correct way to return an interface, in this scenario I am open to the correct implementation.
Attached is a small program that results in an exception:
public static void main(String[] args)
{
Vector v = (Vector) c();
}
static List<Object> c()
{
List<Object> l = new ArrayList<Object>();
l.add(new Object());
List<Object> o = Collections.checkedList(l, Object.class);
return o;
}
The javadoc is here: checked list

The List returned is a Collections.CheckedList not a Vector. You cannot the reference to a type the object is not.
However what you can do is
public static void main(String[] args) {
Vector<Object> v = new Vector<Object>(c());
}
composedObjects is already a List, you can return that.
public List<MyAwesomeComposedObject> convert(Collection<MyAwesomeObject> awesomeObjects>) {
List<MyAwesomeComposedObject> composedObjects = new ArrayList<MyAwesomeComposedObject>();
for(MyAwesomeObject awesomeObject : awesomeObjects)
composedObjects.add(new MyAwesomeComposedObject(awesomeObject));
return composedObjects;
}

For your revised question: There is no way to prevent the caller from attempting to cast to whatever they want. If it is an inappropriate cast they will get the exception. This is the very reason why casting from an interface to a concrete class is strongly discouraged.
If you are really worried about this, consider returning an ArrayList instead of a List. That should discourage casting since they are getting a concrete type. Please note that I do not endorse this, it is just an option.
I want to guarantee that the invoker of this method is getting the interface instead of an implementation
This is not valid. You are returning a List where the declared type of the elements is an interface, however each element must be SOME instantiation. All a checked collection does is prevent the addition of elements of the incorrect type. There is nothing that prevents the user from casting back to the implementation type.
If you are attempting to ensure that the user gets List instead of ArrayList (my assumption here because I don't see an interface for you Awesome class), this again is flawed because the user could still cast the List to an ArrayList although this would be a bad idea since it risks a ClassCastException.

No, I recommend to keep the code as simple as possible. Read the Javadoc for a discussion when to use Collections.checkedList
http://download.oracle.com/javase/7/docs/api/java/util/Collections.html#checkedCollection%28java.util.Collection,%20java.lang.Class%29

Related

Java Collection Type Parameter to array

I want to create a helper method which gets Collection type parameter to return a list. This is what I have now:
public class Helper {
public static <T> T[] CollectionToArray(Collection<T> collection) {
return collection.stream().toArray(Object[]::new); // Error
}
public static <T> T[] ListToArray(List<T> list) {
return list.stream().toArray(Object[]::new); // Error
}
}
public class IamSoNoob {
public void PleaseHelpMe() {
List<String> list = new ArrayList<>();
Set<String> set = new HashSet<>();
String[] arrayFromList = Helper.CollectionToArray(list); // Error
String[] arrayFromSet = Helper.CollectionToArray(set); // Error
String[] array = Helper.ListToArray(list); // Error
}
}
My questions are:
Is it possible to complete CollectionToArray(Collection<T>)?
If so, how?
Also, is it possible to pass List and Set as a parameter in the first place?
Is it possible to complete ListToArray(List<T> list)?
If so, how?
But here are some restrictions due to my personal taste.
I don't want to use #SuppressWarnings
I really want to keep the part .stream().toArray(Object[]::new) (Java 8 part!)
And I have a feeling that I need to fix the part Object[]::new by using something like: <T extends Object> or <? extends T> but I can't really figure out.
Please help me out, and please provide an explanation as well, I am often confused by Generic and ?.
No, you absolutely cannot do it, if it were possible the library method Collection.toArray() would've given you the same type as your LHS but instead when you want the exact type as your LHS you have to use Collection.toArray(T[]) (even that comes with ArrayStoreExceptions i.e it is up to the programmer to provide the right type for the array), the reason being that in your toArray() you've specified Object[] to be your array and later you cannot cast it to any other type or else it will result in a ClassCastException.
The reason for all this hullabaloo is because of the way generics works i.e its a compile time thing and at runtime Java erases all type parameters to their upper bound types and hence losing type information which is required for creating arrays.
One safe way of doing it is by adding another paramter to you helper method as
public static <T> T[] CollectionToArray(Collection<T> collection, T[] arr) {
return collection.stream().toArray(value ->Arrays.copyOf(arr,collection.size()));
}
and using it as
String[] arrayFromList = Helper.CollectionToArray(list, new String[0]);
but then everybody's better off using
Collection#toArray(T[]).

Different Java behavior for Generics and Arrays

Why does java allows inconsistent type to be entered into a generic object reference but not in an array?
For Eg:
When initializing array:
int[] a = {1, 2, 3};
And, if I enter:
int[] a = {1, 2, "3"}; //Error for incompatible types
While for generics,
import java.util.ArrayList;
public class Test {
private static ArrayList tricky(ArrayList list) {
list.add(12345);
return list;
}
public static void main(String[] args) {
int i = 0;
ArrayList<String> list = new ArrayList<>();
list.add("String is King");
Test.tricky(list);
}
}
The above code will let you add any Type in the list object, resulting in a run time exception in some cases.
Why is there such a behavior?? Kindly give a proper explanation.
When you use the tricky method to insert data into your ArrayList Collection, it doesn't match the specified type i.e String, but still This is compatible because of Generics compatibility with older Legacy codes.
If it wouldn't have been for this i.e if it would have been the same way as of arrays, then all of the pre-java generic code would have been broken and all the codes would have to be re-written.
Remember one thing for generics, All your type-specifications are compile time restrictions, so when you use the tricky method to insert data in your list reference, what happens is the compiler thinks of it as a list to which ANYTHING apart from primitives can be added.
Only if you would have written this:
...
public class Test {
private static ArrayList tricky(ArrayList<String> list) {
list.add(12345); //Error, couldn't add Integer to String
return list;
}
...
}
I have written a documented post on this, Read here.
The method's parameter has no generic so all classes are allowed.
You may google 'type erasure' for more information.
If you add the generic type to your method you will get a compiler error:
private static ArrayList<String> tricky(ArrayList<String> list) { // ...
By the way, you do not need to return the list because you modify the same instance.
Here's why:
The reason you can get away with compiling this for arrays is because
there is a runtime exception (ArrayStoreException) that will prevent
you from putting the wrong type of object into an array. If you send a
Dog array into the method that takes an Animal array, and you add only
Dogs (including Dog subtypes, of course) into the array now referenced
by Animal, no problem. But if you DO try to add a Cat to the object
that is actually a Dog array, you'll get the exception. Generic
Methods (Exam Objectives 6.3 and 6.4) 615 616 Chapter 7: Generics and
Collections
But there IS no equivalent exception for generics, because
of type erasure! In other words, at runtime the JVM KNOWS the type of
arrays, but does NOT know the type of a collection. All the generic
type information is removed during compilation, so by the time it gets
to the JVM, there is simply no way to recognize the disaster of
putting a Cat into an ArrayList and vice versa (and it becomes
exactly like the problems you have when you use legacy, non-type safe
code)
Courtesy : SCJP Study guide by Kathy Sierra and Bert Bates
When you declare you ArrayList like ArrayList list = ... you do not declare the type of object your list will contain. By default, since every type has Object as superclass, it is an ArrayList<Object>.
For good practices, you should declare the type of your ArrayList<SomeType> and, thereby, avoid adding inconsistant elements (according to the type)
Because you haven't defined the generic type of your list it defaults to List<Object> which accepts anything that extends Object.
Thanks to auto-boxing a primitive int is converted to an Integer, which extends Object, when it is added to your list.
Your array only allows int's, so String's are not allowed.
This is because in your method parameter you did not specify a particular type for ArrayList so by default it can accept all type of objects.
import java.util.ArrayList;
public class Test {
//Specify which type of objects you want to store in Arraylist
private static ArrayList tricky(ArrayList<String> list) {
list.add(12345); //This will give compile time error now
return list;
}
public static void main(String[] args) {
int i = 0;
ArrayList<String> list = new ArrayList();
list.add("String is King");
Test.tricky(list);
}
}

Without specifying a generic type, method does not return a list of elements, but simply a list

I am having a slight inconvenience when working with generics in Java. Please consider the following code:
/**
* MyElement class is simply a wrapper for a generic object.
*/
public static class MyElement<T> {
public final T OBJ;
public MyElement(T obj) {
this.OBJ = obj;
}
}
/**
* MyElementList contains an array list of MyElements of the given type, T.
* This represents a class that uses a list of MyElements of a certain type,
* and this list can be accessed in an unmodifiable format.
*/
public static class MyElementList<T> {
//Properties
private List<MyElement<T>> elementList = new ArrayList();
//CTOR
public MyElementList(List<MyElement<T>> initElements) {
elementList.addAll(initElements);
}
//Getter
public List<MyElement<T>> getElements() {
return Collections.unmodifiableList(elementList);
}
}
public static void main(String[] args) {
//New list of elements
//Notice that I did not explicitly specify the type for 'MyElement'
List<MyElement> theElements = new ArrayList(Arrays.asList(
new MyElement[] {
new MyElement("E 1"),
new MyElement("E 2"),
new MyElement("E 3")
}
));
//Also notice I did not explicitly specify the type for 'MyElementList'
MyElementList theList = new MyElementList(theElements);
//The following does not work.
//It seems to not work because theList.getElements() returns a 'List'
//not necessarily a 'List<MyElement>' which is what I would expect it to
//return...
//Why???
for(MyElement e : theList.getElements()) {
System.out.println(e.OBJ.toString());
}
//Currently my work around is to do the following, but I do not like
//having to introduce another variable, and I would rather just do the
//one above
List<MyElement> listOfElements = theList.getElements();
for(MyElement e : listOfElements) {
System.out.println(e.OBJ.toString());
}
//How come the first 'for-each' loop method does not work?
//Is there anyway I could get it to work?
//THANK YOU!
}
In the main method, if I don't specify the type parameter for 'MyElementList' the 'getElements()' method only returns a 'List', not a 'List<MyElement>'. This is inconvenient because if I want to iterate through each 'MyElement' I need to introduce another variable as a temporary list, shown in the code.
Why doesn't the 'getElements()' method return a 'List<MyElement>'?
Without making significant changes to 'MyElementList' Is there anything I can do to fix this?
Is this a bad design practice?
The IDE I am using is Netbeans 7.2
Thanks in advance!
EDIT
Thank you all for your quick responses. I am very impressed with the community here. I have concluded the following:
If a generic hint is not specified, Java ignores ALL other associated generic hints for a class - which is kind of lame, but I can live with it.
When using generics, it is a best practice to actually specify the generic type when creating an instance of the class. This seems to be the most object oriented solution.
Thanks again!
If you change MyElementList to look like
public static class MyElementList<T extends MyElement> {
//Properties
private List<T> elementList = new ArrayList<T>();
//CTOR
public MyElementList(List<T> initElements) {
elementList.addAll(initElements);
}
//Getter
public List<T> getElements() {
return Collections.unmodifiableList(elementList);
}
}
It should work.
EDIT Generics can be seen as compile time hints in Java, since Java erasure will convert generics to Object. Updating your class as above will tell the compiler only elements which extend MyElement fit the list and for(MyElement e : theList.getElements()) will work.
EDIT 2 As pointed out by others (sorry, I didn't see it at first glance) also change the raw declaration to:
MyElementList<MyElement> theList = new MyElementList<MyElement>(theElements);
Te first does not work because getElements returns a List<?> for the raw type
The second works because you assigned it to a List<MyElement>, ignoring the warning. Ignoring was ok because you know what it contains, but the compiler doesn't.
Instead of using
for(MyElement e : theList.getElements()) {
System.out.println(e.OBJ.toString());
}
you could use
for (Iterator<MyElement> it = theList.getElements().iterator(); it.hasNext();) {
MyElement e = it.next();
System.out.println(e.next().OBJ.toString());
}
which makes your compiler compliant.
But I would prefer to specify the types that your classes require when instantiating/accessing them (and your compiler too, I guess ;)).
Why doesn't the getElements() method return a List<MyElement>
Because MyElement is typed!
Without making significant changes to MyElementList Is there
anything I can do to fix this?
You can probably use a wildcard:
List<MyElement<?>> someList = getElements();

Java Generics (simple case, clear enigma for infering)

I have this class, just for the purpose of learning:
public class MyClass{ //Looking for a solution without making my class also generic <Type>
//Private Arraylist var to hold the value called myvar
public MyClass(ArrayList<MyDesiredType> incoming) {
//CODE myVar=incoming
}
public MyDesiredType getType() {
return myVar.get(0);
}
}
Is there any way to infer in the incoming object from the constructor to the return type of the method without warnings and castings and loosing typesafeness, but most of all WITHOUT making the whole class GENERIC (seems redundant to me)? If not, why should I think this is not feasible for the compiler?
This is a reformulated question I already did, but it was my first one and I learned how to expose it clear because nobody understood. I tried to edit later the original question but everything was buried. I changed and simplified the example and try to put it easy. Original question: Java Generics Silly Thing (Why cant I infer the type?).
If there is any problem just tell it to me and I will remove it.
No, there is not. How would the compiler know what type to return? The generic type of ArrayList in the constructor will not be known during compile time. You either have to make the whole class generic or take another approach.
Consider this:
public class Test {
public static void main(String[] args) {
List<String> arrList = new ArrayList<String>();
arrList.add("FOO");
Test test = new Test(arrList);
String testStr = test.returnWhat();
System.out.println("testStr");
}
private final List myList; //warning
public <T> Test(List<T> ttype) {
myList = ttype;
}
public <T> T returnWhat() {
return (T) myList.get(0); //warning
}
}
This works but gives you warnings on the marked lines. So, really there is no way to achieve what you are describing without making the whole class generic.
Because, what if:
public class Test {
public static void main(String[] args) {
List<String> arrList = new ArrayList<String>();
arrList.add("FOO");
Test test = new Test(); // now what?
String testStr = test.returnWhat(0); // no warning...
JPanel p = test.returnWhat(0); // goes through without warning, real nice...
test.returnWhat(0); // returns Object
Test test2 = new Test(arrList);
test2.addElement(new Object()); // boom, inserted object into list of string.
String nono = test2.returnWhat(1); // the universe goes down. assign an object to string without warning. even
// though one COULD think the class is generic.
}
// private List<T> myList = new ArrayList<T>(); compiler error, T is unknown
private List myList = new ArrayList();
public Test() {
myList.add(new Object());
}
public <T> Test(List<T> ttype) {
myList = ttype;
}
public <T> T returnWhat(int index) {
return (T) myList.get(index);
}
public <T> void addElement(T el) {
myList.add(el);
}
}
The second one doesn't compile when myList is made generic. How could the compiler determine the type of <T> in the case where the default constructor is used?
Further, this could lead to serious problems with Objects in collections that rely on the fact that only certain types are inserted.
This will generate the following exception:
Exception in thread "main" java.lang.ClassCastException:
java.lang.Object cannot be cast to java.lang.String at
Test.main(Test.java:27)
Did I manage to convince you?
Real nice question, btw. I had to think about this one quite a bit.
When you say that you want the compiler to "infer in the incoming object from the constructor to the return type of the method without warnings and castings and loosing typesafeness", it seems that you are saying that it should infer the result of getType() from the input of the constructor. If both happen in the same function, it could. The problem is that the object may not exist in only one function, and so the extra type information (the generic type) is needed to pass this kind of object between functions.
For example, if I want to write a function that takes a MyClass object, I need to know what getType() will return so I can use the returned value. By adding a generic type of MyClass we are giving a description to what it holds.
Another way to look at it is that MyClass is a container. By adding generics, we are saying it is a container of a specific type of thing, and so we can more easily predict what we will get out of it.
There is no way for the compiler to know at runtime what type your arraylist is. I really dont see the problem using something along the lines of this:
public class MyClass<TYPE> {
private ArrayList<TYPE> incoming;
public MyClass(ArrayList<TYPE> incoming) {
this.incoming = incoming;
}
public TYPE getType() {
return incoming.get(0);
}
}
This way you can do:
ArrayList<Integer> numbers = createListOfNumbers();
MyClass<Integer> myClass = new MyClass<>(numbers);
Integer number = myClass.getType();
Or am i misinterpreting the question and you want to know the class at runtime?
No, if you want a class that can hold a list of a parameterized type.
Yes, if you want a class that can hold a list of exactly one type. You can declare that type explicitly in the field, constructor and accessor.
What you're forgetting is that not all code that you may run against is visible to the compiler! Jars can be added, removed, substituted at run time, that the compiler never saw. You may compile against an interface that is just:
public interface MyClassFactory {
MyClass getInstance();
}
Then at runtime you supply into the JVM an implementation. So the compiler never saw the actual code creating the MyClass that you will be using, so there is no way to perform such a compile time inference. You must either make the class generic or accept that there will not be type safety.

How do you cast a List of supertypes to a List of subtypes?

For example, lets say you have two classes:
public class TestA {}
public class TestB extends TestA{}
I have a method that returns a List<TestA> and I would like to cast all the objects in that list to TestB so that I end up with a List<TestB>.
Simply casting to List<TestB> almost works; but it doesn't work because you can't cast a generic type of one parameter to another. However, you can cast through an intermediate wildcard type and it will be allowed (since you can cast to and from wildcard types, just with an unchecked warning):
List<TestB> variable = (List<TestB>)(List<?>) collectionOfListA;
Casting of generics is not possible, but if you define the list in another way it is possible to store TestB in it:
List<? extends TestA> myList = new ArrayList<TestA>();
You still have type checking to do when you are using the objects in the list.
With Java 8, you actually can
List<TestB> variable = collectionOfListA
.stream()
.map(e -> (TestB) e)
.collect(Collectors.toList());
You really can't*:
Example is taken from this Java tutorial
Assume there are two types A and B such that B extends A.
Then the following code is correct:
B b = new B();
A a = b;
The previous code is valid because B is a subclass of A.
Now, what happens with List<A> and List<B>?
It turns out that List<B> is not a subclass of List<A> therefore we cannot write
List<B> b = new ArrayList<>();
List<A> a = b; // error, List<B> is not of type List<A>
Furthermore, we can't even write
List<B> b = new ArrayList<>();
List<A> a = (List<A>)b; // error, List<B> is not of type List<A>
*: To make the casting possible we need a common parent for both List<A> and List<B>: List<?> for example. The following is valid:
List<B> b = new ArrayList<>();
List<?> t = (List<B>)b;
List<A> a = (List<A>)t;
You will, however, get a warning. You can suppress it by adding #SuppressWarnings("unchecked") to your method.
I think you are casting in the wrong direction though... if the method returns a list of TestA objects, then it really isn't safe to cast them to TestB.
Basically you are asking the compiler to let you perform TestB operations on a type TestA that does not support them.
Since this is a widely referenced question, and the current answers mainly explain why it does not work (or propose hacky, dangerous solutions that I would never ever like to see in production code), I think it is appropriate to add another answer, showing the pitfalls, and a possible solution.
The reason why this does not work in general has already been pointed out in other answers: Whether or not the conversion is actually valid depends on the types of the objects that are contained in the original list. When there are objects in the list whose type is not of type TestB, but of a different subclass of TestA, then the cast is not valid.
Of course, the casts may be valid. You sometimes have information about the types that is not available for the compiler. In these cases, it is possible to cast the lists, but in general, it is not recommended:
One could either...
... cast the whole list or
... cast all elements of the list
The implications of the first approach (which corresponds to the currently accepted answer) are subtle. It might seem to work properly at the first glance. But if there are wrong types in the input list, then a ClassCastException will be thrown, maybe at a completely different location in the code, and it may be hard to debug this and to find out where the wrong element slipped into the list. The worst problem is that someone might even add the invalid elements after the list has been casted, making debugging even more difficult.
The problem of debugging these spurious ClassCastExceptions can be alleviated with the Collections#checkedCollection family of methods.
Filtering the list based on the type
A more type-safe way of converting from a List<Supertype> to a List<Subtype> is to actually filter the list, and create a new list that contains only elements that have certain type. There are some degrees of freedom for the implementation of such a method (e.g. regarding the treatment of null entries), but one possible implementation may look like this:
/**
* Filter the given list, and create a new list that only contains
* the elements that are (subtypes) of the class c
*
* #param listA The input list
* #param c The class to filter for
* #return The filtered list
*/
private static <T> List<T> filter(List<?> listA, Class<T> c)
{
List<T> listB = new ArrayList<T>();
for (Object a : listA)
{
if (c.isInstance(a))
{
listB.add(c.cast(a));
}
}
return listB;
}
This method can be used in order to filter arbitrary lists (not only with a given Subtype-Supertype relationship regarding the type parameters), as in this example:
// A list of type "List<Number>" that actually
// contains Integer, Double and Float values
List<Number> mixedNumbers =
new ArrayList<Number>(Arrays.asList(12, 3.4, 5.6f, 78));
// Filter the list, and create a list that contains
// only the Integer values:
List<Integer> integers = filter(mixedNumbers, Integer.class);
System.out.println(integers); // Prints [12, 78]
You cannot cast List<TestB> to List<TestA> as Steve Kuo mentions BUT you can dump the contents of List<TestA> into List<TestB>. Try the following:
List<TestA> result = new List<TestA>();
List<TestB> data = new List<TestB>();
result.addAll(data);
I've not tried this code so there are probably mistakes but the idea is that it should iterate through the data object adding the elements (TestB objects) into the List. I hope that works for you.
The best safe way is to implement an AbstractList and cast items in implementation. I created ListUtil helper class:
public class ListUtil
{
public static <TCastTo, TCastFrom extends TCastTo> List<TCastTo> convert(final List<TCastFrom> list)
{
return new AbstractList<TCastTo>() {
#Override
public TCastTo get(int i)
{
return list.get(i);
}
#Override
public int size()
{
return list.size();
}
};
}
public static <TCastTo, TCastFrom> List<TCastTo> cast(final List<TCastFrom> list)
{
return new AbstractList<TCastTo>() {
#Override
public TCastTo get(int i)
{
return (TCastTo)list.get(i);
}
#Override
public int size()
{
return list.size();
}
};
}
}
You can use cast method to blindly cast objects in list and convert method for safe casting.
Example:
void test(List<TestA> listA, List<TestB> listB)
{
List<TestB> castedB = ListUtil.cast(listA); // all items are blindly casted
List<TestB> convertedB = ListUtil.<TestB, TestA>convert(listA); // wrong cause TestA does not extend TestB
List<TestA> convertedA = ListUtil.<TestA, TestB>convert(listB); // OK all items are safely casted
}
The only way I know is by copying:
List<TestB> list = new ArrayList<TestB> (
Arrays.asList (
testAList.toArray(new TestB[0])
)
);
When you cast an object reference you are just casting the type of the reference, not the type of the object. casting won't change the actual type of the object.
Java doesn't have implicit rules for converting Object types. (Unlike primitives)
Instead you need to provide how to convert one type to another and call it manually.
public class TestA {}
public class TestB extends TestA{
TestB(TestA testA) {
// build a TestB from a TestA
}
}
List<TestA> result = ....
List<TestB> data = new List<TestB>();
for(TestA testA : result) {
data.add(new TestB(testA));
}
This is more verbose than in a language with direct support, but it works and you shouldn't need to do this very often.
Answering in 2022
Casting a List of supertypes to a List of subtypes is nonsensical and nobody should be attempting or even contemplating doing such a thing. If you think your code needs to do this, you need to rewrite your code so that it does not need to do this.
Most visitors to this question are likely to want to do the opposite, which does actually make sense:
Cast a list of subtypes to a list of supertypes.
The best way I have found is as follows:
List<TestA> testAs = List.copyOf( testBs );
This has the following advantages:
It is a neat one-liner
It produces no warnings
It does not make a copy if your list was created with List.of() !!!
Most importantly: it does the right thing.
Why is this the right thing?
If you look at the source code of List.copyOf() you will see that it works as follows:
If your list was created with List.of(), then it will do the cast and return it without copying it.
Otherwise, (e.g. if your list is an ArrayList(),) it will create a copy and return it.
If your List<TestB> is an ArrayList<TestB> then a copy of the ArrayList must be made. If you were to cast the ArrayList<TestB> as List<TestA>, you would be opening up the possibility of inadvertently adding a TestA into that List<TestA>, which would then cause your original ArrayList<TestB> to contain a TestA among the TestBs, which is memory corruption: attempting to iterate all the TestBs in the original ArrayList<TestB> would throw a ClassCastException.
On the other hand, if your List<TestB> has been created using List.of(), then it is unchangeable(*1), so nobody can inadvertently add a TestA to it, so it is okay to just cast it to List<TestA>.
(*1) when these lists were first introduced they were called "immutable"; later they realized that it is wrong to call them immutable, because a collection cannot be immutable, since it cannot vouch for the immutability of the elements that it contains; so they changed the documentation to call them "unmodifiable" instead; however, "unmodifiable" already had a meaning before these lists were introduced, and it meant "an unmodifiable to you view of my list which I am still free to mutate as I please, and the mutations will be very visible to you". So, neither immutable or unmodifiable is correct. I like to call them "superficially immutable" in the sense that they are not deeply immutable, but that may ruffle some feathers, so I just called them "unchangeable" as a compromise.
if you have an object of the class TestA, you can't cast it to TestB. every TestB is a TestA, but not the other way.
in the following code:
TestA a = new TestA();
TestB b = (TestB) a;
the second line would throw a ClassCastException.
you can only cast a TestA reference if the object itself is TestB. for example:
TestA a = new TestB();
TestB b = (TestB) a;
so, you may not always cast a list of TestA to a list of TestB.
You can use the selectInstances method in Eclipse Collections. This will involved creating a new collection however so will not be as efficient as the accepted solution which uses casting.
List<CharSequence> parent =
Arrays.asList("1","2","3", new StringBuffer("4"));
List<String> strings =
Lists.adapt(parent).selectInstancesOf(String.class);
Assert.assertEquals(Arrays.asList("1","2","3"), strings);
I included StringBuffer in the example to show that selectInstances not only downcasts the type, but will also filter if the collection contains mixed types.
Note: I am a committer for Eclipse Collections.
This is possible due to type erasure. You will find that
List<TestA> x = new ArrayList<TestA>();
List<TestB> y = new ArrayList<TestB>();
x.getClass().equals(y.getClass()); // true
Internally both lists are of type List<Object>. For that reason you can't cast one to the other - there is nothing to cast.
The problem is that your method does NOT return a list of TestA if it contains a TestB, so what if it was correctly typed? Then this cast:
class TestA{};
class TestB extends TestA{};
List<? extends TestA> listA;
List<TestB> listB = (List<TestB>) listA;
works about as well as you could hope for (Eclipse warns you of an unchecked cast which is exactly what you are doing, so meh). So can you use this to solve your problem? Actually you can because of this:
List<TestA> badlist = null; // Actually contains TestBs, as specified
List<? extends TestA> talist = badlist; // Umm, works
List<TextB> tblist = (List<TestB>)talist; // TADA!
Exactly what you asked for, right? or to be really exact:
List<TestB> tblist = (List<TestB>)(List<? extends TestA>) badlist;
seems to compile just fine for me.
Quite strange that manually casting a list is still not provided by some tool box implementing something like:
#SuppressWarnings({ "unchecked", "rawtypes" })
public static <T extends E, E> List<T> cast(List<E> list) {
return (List) list;
}
Of course, this won't check items one by one, but that is precisely what we want to avoid here, if we well know that our implementation only provides the sub-type.
class MyClass {
String field;
MyClass(String field) {
this.field = field;
}
}
#Test
public void testTypeCast() {
List<Object> objectList = Arrays.asList(new MyClass("1"), new MyClass("2"));
Class<MyClass> clazz = MyClass.class;
List<MyClass> myClassList = objectList.stream()
.map(clazz::cast)
.collect(Collectors.toList());
assertEquals(objectList.size(), myClassList.size());
assertEquals(objectList, myClassList);
}
This test shows how to cast List<Object> to List<MyClass>. But you need to take an attention to that objectList must contain instances of the same type as MyClass. And this example can be considered when List<T> is used. For this purpose get field Class<T> clazz in constructor and use it instead of MyClass.class.
UPDATED
Actually you can't cast from supertype to subtype in strong typed Java AFAIK. But you can introduce an interface that the supertype implements.
interface ITest {
}
class TestA implements ITest {
}
class TestB extends TestA {
}
public class Main {
public static void main(String[] args) {
List<ITest> testAList = Arrays.asList(new TestA(), new TestA());
Class<ITest> clazz = ITest.class;
List<ITest> testBList = testAList.stream()
.map(clazz::cast)
.collect(Collectors.toList());
System.out.println(testBList.size());
System.out.println(testAList);
}
}
Or you can cast from subtype to supertype. Like this:
class TestA {
}
class TestB extends TestA {
}
public class Main {
public static void main(String[] args) {
var a = new TestA();
var b = new TestB();
System.out.println(((TestA) b));
List<TestB> testBList = Arrays.asList(new TestB(), new TestB());
Class<TestA> clazz = TestA.class;
List<TestA> testAList = testBList.stream()
.map(clazz::cast)
.collect(Collectors.toList());
System.out.println(testAList.size());
System.out.println(testAList);
}
}
FYI my original answer pointed on a possibility of using it with generics. In fact I took it from my Hibernate DAO code.
Simple answer
You can't directly type cast.
Workaround
public <T> List<T> getSubItemList(List<IAdapterImage> superList, Class<T> clazz) {
return superList.stream()
.map(item -> clazz.isInstance(item) ? clazz.cast(item) : null)
.collect(Collectors.toList());
}
Usage
private final List<IAdapterImage> myList = new ArrayList<>();
List<SubType> subTypeList = getSubItemList(myList,SubType.class);
So this is simple workaround I use to convert my list with super type into list with subtype. We are using stream api which was introduced in java 8 here, using map on our super list we are simply checking if passed argument is instance of our super type the returning the item. At last we are collecting into a new list. Of course we have to get result into a new list here.
I had to do this implementation in a method of the company's system:
interface MyInterface{}
Class MyClass implements MyInterface{}
The method receives an interface list, that is, I already have an interface list instantiated
private get(List<MyInterface> interface) {
List<MyClass> myClasses = interface.stream()
.filter(MyClass.class::isInstance)
.map(MyClass.class::cast)
.collect(Collectors.toList());
}
This should would work
List<TestA> testAList = new ArrayList<>();
List<TestB> testBList = new ArrayList<>()
testAList.addAll(new ArrayList<>(testBList));

Categories

Resources