Dieser Inhalt ist in der von Ihnen ausgewählten Sprache nicht verfügbar.

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
Nach oben
Red Hat logoGithubredditYoutubeTwitter

Lernen

Testen, kaufen und verkaufen

Communitys

Über Red Hat Dokumentation

Wir helfen Red Hat Benutzern, mit unseren Produkten und Diensten innovativ zu sein und ihre Ziele zu erreichen – mit Inhalten, denen sie vertrauen können. Entdecken Sie unsere neuesten Updates.

Mehr Inklusion in Open Source

Red Hat hat sich verpflichtet, problematische Sprache in unserem Code, unserer Dokumentation und unseren Web-Eigenschaften zu ersetzen. Weitere Einzelheiten finden Sie in Red Hat Blog.

Über Red Hat

Wir liefern gehärtete Lösungen, die es Unternehmen leichter machen, plattform- und umgebungsübergreifend zu arbeiten, vom zentralen Rechenzentrum bis zum Netzwerkrand.

Theme

© 2025 Red Hat