java - TRying to creat a stack class whare on class can handle diffrent data types -
i created class simulate stack. right type fixed float. i'v seen in java util class have stack class ware can define type.
i not find on how creat class type 1 of verbols can define when object created. tried googling java template totiol, think in c called templates.
so have classpublic class cstack {
float data[]; int size=0; int pes=0; cstack(int size) { data=new float[size]; pes=0; }
now data def float, when create class can set type. can hold floats, or integers or strings.
this generic linkedstack implementation bruce eckel's "thinking in java":
public class linkedstack<t> { private static class node<u> { u item; node<u> next; node() { item = null; next = null; } node(u item, node<u> next) { this.item = item; this.next = next; } boolean end() { return item == null && next == null; } } private node<t> top = new node<t>(); // end sentinel public void push(t item) { top = new node<t>(item, top); } public t pop() { t result = top.item; if (!top.end()) top = top.next; return result; } public static void main(string[] args) { linkedstack<string> lss = new linkedstack<string>(); (string s : "phasers on stun!".split(" ")) lss.push(s); string s; while ((s = lss.pop()) != null) system.out.println(s); } }
i'll recommend read whole book , "generics" chapter.
Comments
Post a Comment