SERPland Flugverkehr/Airtraffic Zürich – Auto Direktimport Dänemark – Disneyland Paris – Legoland Deutschland

4Jun/070

pl/sql integer stack with object types

In the object oriented word, an "intStack" is pretty well known. But how can I do this with Oracles pl/sql?
Just use an object type:


CREATE or replace TYPE IntArray AS VARRAY(50) OF INTEGER;
/
CREATE or replace TYPE IntStack_O AS OBJECT (
maximalSize INTEGER

,top INTEGER
,position IntArray
,MEMBER PROCEDURE initialize
,MEMBER FUNCTION full RETURN BOOLEAN
,MEMBER FUNCTION empty RETURN BOOLEAN
,MEMBER FUNCTION getAnzahl RETURN INTEGER
,MEMBER PROCEDURE push (n IN INTEGER)
,MEMBER PROCEDURE pop (n OUT INTEGER)
);
/


CREATE or replace TYPE body IntStack_O AS
MEMBER PROCEDURE initialize IS
BEGIN
top := 0;
-- Call Constructor und set element 1 to NULL
position := IntArray(NULL);
maximalSize := position.LIMIT; -- Get Varray Size
position.EXTEND(maximalSize -1, 1); -- copy elements 1 in 2..50
END initialize;

MEMBER FUNCTION full RETURN BOOLEAN IS
BEGIN
RETURN (top = maximalSize); -- Return TRUE when Stack is full
END full;

MEMBER FUNCTION empty RETURN BOOLEAN IS
BEGIN
RETURN (top = 0); -- Return TRUE when Stack is empty
END empty;

MEMBER FUNCTION getAnzahl RETURN integer IS
BEGIN
RETURN top;
END;

MEMBER PROCEDURE push (n IN INTEGER) IS
BEGIN
IF NOT full
THEN
top := top + 1; -- Push Integer onto the stack
position(top) := n;
ELSE
--Stack ist voll!
RAISE_APPLICATION_ERROR(-20101, 'Error! Stack overflow. '
||'limit for stacksize reached.');
END IF;
END push;

MEMBER PROCEDURE pop (n OUT INTEGER) IS
BEGIN
IF NOT empty
THEN
n := position(top);
top := top -1; -- take top element from stack
ELSE
--Stack ist leer!
RAISE_APPLICATION_ERROR(-20102, 'Error! Stack underflow. '
||'stack is empty.');
END IF;
END pop;
END;

This pl/sql code is easy. Now let's run ...
... and do some push and popps ....


DECLARE
stack intstack_o := intstack_o(NULL,NULL,NULL);
a INTEGER;
BEGIN
stack.initialize;
dbms_output.put_line('Anzahl: ' || stack.getAnzahl);
stack.push(1111);
dbms_output.put_line('Anzahl: ' || stack.getAnzahl);
stack.push(1112);
dbms_output.put_line('Anzahl: ' || stack.getAnzahl);
stack.push(1113);
dbms_output.put_line('Anzahl: ' || stack.getAnzahl);
stack.pop(a);
dbms_output.put_line('Anzahl: ' || stack.getAnzahl);
dbms_output.put_line(a);
stack.pop(a);
dbms_output.put_line('Anzahl: ' || stack.getAnzahl);
dbms_output.put_line(a);
stack.pop(a);
dbms_output.put_line('Anzahl: ' || stack.getAnzahl);
dbms_output.put_line(a);
stack.pop(a);
dbms_output.put_line('Anzahl: ' || stack.getAnzahl);
dbms_output.put_line(a);
END;

Here's the result:

Anzahl: 0
Anzahl: 1
Anzahl: 2
Anzahl: 3
Anzahl: 2
1113
Anzahl: 1
1112
Anzahl: 0
1111

Related Posts:

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

No trackbacks yet.