---
schema_version: "1"
id: 1077154e0a6e494e2410e4c53e4c9712472ddce0242c8d18d15498386a41c493
title: Collection Casting
collection: legacydeveloper
version: current
locale: en-us
portal_url: https://docs.salesforce.com/legacydeveloper/current/en-us/apexcode/apex_classes_casting_collections.md
canonical_url: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_casting_collections.htm
source_site: developer.salesforce.com
content_type: documentation
content_hash: 849b12eb7f5829548bd185e5d2132b0ba374b8a41163b1460b669a419be40629
---
# Collection Casting

Because collections in Apex have a declared type at runtime, Apex allows collection casting.

Collections can be cast in a similar manner that arrays can be cast in Java. For example, a list of CustomerPurchaseOrder objects can be assigned to a list of PurchaseOrder objects if class CustomerPurchaseOrder is a child of class PurchaseOrder.

public virtual with sharing class PurchaseOrder {
}

public with sharing class CustomerPurchaseOrder extends PurchaseOrder {
}

List<CustomerPurchaseOrder> CPOs = new List<CustomerPurchaseOrder>();
List<PurchaseOrder> POs = CPOs;

// This cast succeeds because POs still has the runtime type List<CustomerPurchaseOrder>.
List<CustomerPurchaseOrder> restored = (List<CustomerPurchaseOrder>) POs;

// This cast fails at runtime because genericOrders was instantiated as List<PurchaseOrder>.
// List<PurchaseOrder> genericOrders = new List<PurchaseOrder>();
// List<CustomerPurchaseOrder> invalid = (List<CustomerPurchaseOrder>) genericOrders;

Once the CustomerPurchaseOrder list is assigned to the PurchaseOrder list variable, it can be cast back to a list of CustomerPurchaseOrder objects, but only because that instance was originally instantiated as a list of CustomerPurchaseOrder objects. A list of PurchaseOrder objects that is instantiated as such cannot be cast to a list of CustomerPurchaseOrder objects, even if the list of PurchaseOrder objects contains only CustomerPurchaseOrder objects.

If the user of a PurchaseOrder list that only includes CustomerPurchaseOrder objects tries to insert a non-CustomerPurchaseOrder subclass of PurchaseOrder (such as InternalPurchaseOrder), a runtime exception results. This is because Apex collections have a declared type at runtime.

![Note](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/images/icon_note.png)

#### Note

Maps behave in the same way as lists with regards to the value side of the Map. If the value side of map A can be cast to the value side of map B, and they have the same key type, then map A can be cast to map B. A runtime error results if the casting is not valid with the particular map at runtime.

- [← Previous](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_collections.htm "Classes and Collections")