• Post Reply Bookmark Topic Watch Topic
  • New Topic

Typecasting interface to ArrayList  RSS feed

 
Amit kumar dubey
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can i type cast a interface to ArrayList? suppose there is a interface Named Node.
public interface Node
{
public static final short ELEMENT_NODE=1;
......
.....
}

i want to typecast this interface to ArrayList and fetch all the value.could any one please Answer with Example.you can use hashtable object class etc.my main moto is to take a value in ArrayList and traverse it.
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The bit of code you posted doesn't look like an ArrayList, so you can't cast it to one. You can only cast X to Y if X is a Y to begin with.
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think it is unfortunate that they use the same word “cast” for primitives and references. In the case of primitives casting does change the type of the variable (and may even change its value).
If you cast references you cannot change their type.


And welcome to the Ranch
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you mean that you have a Node object and you want to cast that to an ArrayList, like this?

No, you cannot do that.

Casting is no magic wand that can convert any type of object to an arbitrary different type of object. The only thing that a cast does, is tell the compiler that you know better than the compiler what kind of object you have - so you tell the compiler that it should treat the object as if it is of the type you specify. When you run the program, the JVM will check if the object you're casting is indeed of the type you say it is - and if it is not, you will get a ClassCastException.

And when you try to cast a Node to an ArrayList, it will not even compile, because the compiler can already see that Node and ArrayList are unrelated types (Node is not a subclass of ArrayList), so it knows that such a cast can never work.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!