Using Throwable to store data in buffers and "throwing" data
Hi. This is my first post. I am taking an undergraduate course in Java; Algorithms and Data structure. I am not sure if that is qualified as advanced material here. I assumed it was not. (Note to admin: Please do move to the correct topic where this post belongs - I was uncertain regarding the complexity of my question which I shall pose now)
I wish to achieve the following code :
Code:
if (data instanceof Type1) {
// put data in buffer1
} else if (data instanceof Type2) {
// putt data i buffer2
That is the main goal I wish to achieve using class Throwable. Why ? Just for the sake of it I guess. No good reason I can up with :)
Please be warned that the following code is just my attempt at solving the question I have posed, and in no way is correct :D It can be compiled though :p
Here is the code I have written :
Would really appreciate any tips regarding posting code. For instance a site which can maintain the structure of a text editor.
EDIT : I found the site which can store your code after googling a little :) Here is the code : http://pastebin.com/VwhgdpBE
Code:
import java.util.ArrayList;
class Test {
public static void main(String [] args) {
Throw test = new Throw();
test.add();
try {
test.fillBuffer1();
}
catch(Type2 t1) {
try {
test.fillBuffer2();
}
catch(Type1 t2) {
// no need to do anything
}
}
}
}
class Throw {
public volatile static ArrayList <Type1> Buffer1 = new ArrayList<Type1> ();
public volatile static ArrayList <Type2> Buffer2 = new ArrayList<Type2> ();
public volatile static ArrayList <Object> MixedBuffer = new ArrayList<Object>() ;
public void add() {
MixedBuffer.add(new Type1("Jason"));
MixedBuffer.add(new Type2(96));
MixedBuffer.add(new Type1("Joe"));
MixedBuffer.add(new Type2(342316));
MixedBuffer.add(new Type2(13123));
MixedBuffer.add(new Type1("Jim"));
MixedBuffer.add(new Type1("Jake"));
MixedBuffer.add(new Type1("Jill"));
}
// throws the wrong type to the correct method which can insert it
// in the correct buffer. how do I do that ?
public synchronized void fillBuffer2() throws Type1 {
if(MixedBuffer.isEmpty()) {
return;
}
Buffer2.add((Type2)MixedBuffer.remove(0));
fillBuffer2();
}
// throws the wrong type to the correct method which can insert it
// in the correct buffer. how do I do that ?
public synchronized void fillBuffer1() throws Type2 {
if(MixedBuffer.isEmpty()) {
return;
}
Buffer1.add((Type1)MixedBuffer.remove(0));
fillBuffer1();
}
}
class Type1 extends Throwable {
public String data;
public Type1(String data) {
this.data = data;
}
}
class Type2 extends Throwable {
public int data;
Type2(int data) {
this.data = data;
}
}
Moderator Edit: Code tags added