Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /
Tipos de datos

Collections - Java SDK

A Realm collection is an object that contains zero or more instances of one type. Realm collections are homogenous, i.e. all objects in a collection are of the same type.

You can filter and sort any collection using Realm's query engine. Collections are live, so they always reflect the current state of the realm instance on the current thread. You can also listen for changes in the collection by subscribing to collection notifications.

Realm tiene dos tipos de colecciones: listas y resultados.

Los objetos de Realm pueden contener listas de tipos de datos que no son de Realm. Puedes modelar estas colecciones con el tipo RealmList<T>, donde T puede ser de los siguientes tipos:

  • String

  • Integer

  • UUID

  • ObjectId

  • Boolean

  • Float

  • Double

  • Short

  • Long

  • Byte

  • byte[]

  • Date

Tip

A list collection represents a to-many relationship between two Realm types. Lists are mutable: within a write transaction, you can add and remove elements on a list. Lists are not associated with a query.

A results collection represents the lazily-evaluated results of a query operation. Results are immutable: you cannot add or remove elements on the results collection. Results have an associated query that determines their contents.

La La claseRealmResults hereda de AbstractListY se comporta de forma similar. Por ejemplo, RealmResults está ordenado y se puede acceder a los objetos individuales mediante un índice. Si una consulta no encuentra coincidencias, el RealmResults objeto devuelto será una lista de 0 longitud, no una null referencia a un objeto.

Solo puedes modificar o eliminar objetos en un conjunto RealmResults en una transacción de escritura.

Dado que las colecciones de Realm son objetos activos, pueden moverse a medida que se recorre una colección. Puedes usar snapshots para recorrer las colecciones de forma segura.

Realm offers adapters to help bind data to standard UI widgets. These classes work with any class that implements the OrderedRealmCollection interface, which includes the built-in RealmResults and RealmList classes. For more information on adapters, see the documentation on Displaying Collections.

Importante

Adapters Require Managed Objects

Los adaptadores de Realm solo aceptan instancias de objetos Realm gestionados asociados a una instancia de un realm. Para mostrar objetos no gestionados, utiliza el Android RecyclerView.Adapter de uso general para vistas recursivas o ArrayAdapter para vistas de lista.

Like live objects, Realm collections are usually live:

  • Live results collections always reflect the current results of the associated query.

  • Live lists always reflect the current state of the relationship on the realm instance.

Hay tres casos en los que una colección no está en vivo:

  • La colección no está gestionada, por ejemplo, una propiedad List de un objeto Realm que aún no se ha añadido a un Realm o que ha sido copiada desde un Realm.

  • The collection is frozen.

  • The collection is part of a snapshot.

Combined with collection notifications, live collections enable clean, reactive code. For example, suppose your view displays the results of a query. You can keep a reference to the results collection in your view class, then read the results collection as needed without having to refresh it or validate that it is up-to-date.

Advertencia

Indexes may change

Los resultados se actualizan automáticamente. Si almacena el índice posicional de un objeto en una colección o el conteo de objetos en una colección, el valor almacenado del índice o conteo podría estar desactualizado cuando lo utilice.

Realm solo ejecutar una consulta cuando realmente se hace una solicitud de los resultados de esa query, por ejemplo, al acceder a elementos de la colección de resultados. Esta evaluación perezosa te permite escribir código elegante y de alto rendimiento para manejar grandes conjuntos de datos y queries complejas.

As a result of lazy evaluation, you do not need any special mechanism to limit query results with Realm. For example, if your query matches thousands of objects, but you only want to load the first ten, simply access only the first ten elements of the results collection.

Thanks to lazy evaluation, the common task of pagination becomes quite simple. For example, suppose you have a results collection associated with a query that matches thousands of objects in your realm. You display one hundred objects per page. To advance to any page, simply access the elements of the results collection starting at the index that corresponds to the target page.

When you need a collection, you can use the following rule of thumb to determine whether a list or a results collection is appropriate:

To understand these different use cases, consider whether you should be able to add or remove objects directly. Lists allow you to add and remove objects directly, because you control the relationships. Results collections do not allow you to add or remove objects directly, because their contents are determined by a query.

Ejemplo

Consider a Realm type called Person with a field called emails that is a collection of strings representing email addresses. You control this data. Your application needs to add and remove email addresses from your Person instances. Therefore, use a list to define the field type of emails.

On the other hand, when you query the realm for all Persons over the age of 25, it would not make sense for you to add or remove Persons directly to the resulting collection. The contents of that collection only change when the query matches a different set of Persons. Therefore, Realm gives you a results collection.

Nota

Inverse one-to-many relationships

Since Realm automatically determines the contents of implicit inverse relationship collections, you may not add or remove objects from such a collection. Therefore, the type of such a one-to-many relationship property is actually a results collection, not a list.

Volver

tipos de campo

En esta página