Este conteúdo não está disponível no idioma selecionado.

10.2.6. Example


Example 10.7, “Saving and Restoring an Object's State” shows a basic Array class derived from the StateManager class. To illustrate saving and restoring of an object’s state, the highestIndex variable keeps track of the highest element of the array that has a non-zero value.

Example 10.7. Saving and Restoring an Object's State

public class Array extends StateManager
{
    public Array ();
    public Array (Uid objUid);
    public void finalize ( super.terminate(); };
      
    /* Class specific operations. */
      
    public boolean set (int index, int value);
    public int get (int index);
      
    /* State management specific operations. */
      
    public boolean save_state (OutputObjectState os, int ObjectType);
    public boolean restore_state (InputObjectState os, int ObjectType);
    public String type ();
      
    public static final int ARRAY_SIZE = 10;
      
    private int[] elements = new int[ARRAY_SIZE];
    private int highestIndex;
};
Copy to Clipboard Toggle word wrap
The save_state, restore_state and type operations can be defined as follows:
/* Ignore ObjectType parameter for simplicity */

public boolean save_state (OutputObjectState os, int ObjectType)
{
    if (!super.save_state(os, ObjectType))
	return false;
      
    try
	{    
	    packInt(highestIndex);

	    /*
	     * Traverse array state that we wish to save. Only save active elements
	     */

	    for (int i = 0; i <= highestIndex; i++)
		os.packInt(elements[i]);
      
	    return true;
	}
    catch (IOException e)
	{
	    return false;
	}
}
      
public boolean restore_state (InputObjectState os, int ObjectType)
{
    if (!super.restore_state(os, ObjectType))
	return false;
      
    try
	{
	    int i = 0;
      
	    highestIndex = os.unpackInt();
      
	    while (i < ARRAY_SIZE)
		{
		    if (i <= highestIndex)
			elements[i] =  os.unpackInt();
		    else
			elements[i] = 0;
		    i++;
		}
      
	    return true;
	}
    catch (IOException e)
	{
	    return false;
	}
}
      
public String type ()
{
    return '/StateManager/Array';
}
Copy to Clipboard Toggle word wrap
Voltar ao topo
Red Hat logoGithubredditYoutubeTwitter

Aprender

Experimente, compre e venda

Comunidades

Sobre a documentação da Red Hat

Ajudamos os usuários da Red Hat a inovar e atingir seus objetivos com nossos produtos e serviços com conteúdo em que podem confiar. Explore nossas atualizações recentes.

Tornando o open source mais inclusivo

A Red Hat está comprometida em substituir a linguagem problemática em nosso código, documentação e propriedades da web. Para mais detalhes veja o Blog da Red Hat.

Sobre a Red Hat

Fornecemos soluções robustas que facilitam o trabalho das empresas em plataformas e ambientes, desde o data center principal até a borda da rede.

Theme

© 2025 Red Hat