I'm trying to make a symbol table, for a project. The project as a whole is a translator/compiler that translates an imaginary language into java. I have everything down except for the symbol table.

I am currently using a Stack of Lists. The Lists are vectors of Strings

so I have Stack<Vector<String>>

What I'm trying to do is make a List of the declared variables, then when a nested class occurs, I push the current list on top of the stack. Now my problem is that I need to clear the current List so that I can hold only the declared variables in the new inner class with the list. But if I clear the List it also clears it from the Stack, because its an object and thus they are aliases (I'm assuming). Could any one suggest a way to clear the current List without affecting what I have on the Stack?

Here's My code for my Symbol Table

public void Check()
	{
		for(int j=0; j<tIndex; j++)
		{
			while(tokens[j].equals("var")||tokens[j].equals(","))
			{
				j++;
				if(idcheck(tokens[j]))
				{
					if(reName(tokens[j]))
					{
							change(tokens[j], blockNumber, j);		
					}
					if(!reDeclaredV(tokens[j]))
						vVariables.add(tokens[j]);
					else 
						System.out.println("error");
				}
			}
			
			if(tokens[j].equals("const"))
			{
				j++;
				if(idcheck(tokens[j]))
				{
					if(!reDeclaredC(tokens[j]))
						vConstatns.add(tokens[j]);
					else
						System.out.println("error");
				}
			}

			if(tokens[j].equals("loop")||tokens[j].equals("if"))
			{
				Vector<String> temp= new Vector<String>();
				temp=vVariables;
				variables.push(temp);
				blockNumber++;
				vVariables.clear();
			}
			if(tokens[j].equals("end"))
			{
				vVariables=variables.pop();
				blockNumber--;
				
			}
		}
	}

I only posted the method in question

Thanks for any help

Vector and hence Stack are legacy/by default thread safe classes. Consider using ArrayList and LinkedList in lieu of the above mentioned classes.

And as for your problem, replace:

Vector<String> temp= new Vector<String>();
temp  =vVariables;
variables.push(temp);

with

variables.push(new Vector<String>(vVariables));

In your code, you create a new Vector instance referenced by `temp' but discard it by assigning `vVariables' to `temp' which effectively means, `vVariables' and `temp' now point to the same thing. In the code I posted, the list pushed onto the `variables' stack is effectively different from the list `vVariables'. It is also worth noticing that both the lists effectively point to the same data so modifying it will make the changes visible in both the lists [which isn't a problem here since Strings are immutable].

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.