java - Generics and ArrayList -
how can access methods in students class. when print mylist uses tostring in students class, i'm not sure how access other methods. possible?
ps have try , catch in program, didn't post here make code shorter.
public class databaseaccess <t> { public t[] database; public arraylist<t>mylist = new arraylist<t>(); public arraylist<t> testlist = new arraylist<t>(); public void userinterface(){ int count = 1; (t : mylist){ system.out.println(count++ + ": " + i); } } public void readdatabase(){ try { objectinputstream in = new objectinputstream(new fileinputstream("grocery.bin")); database = (t[]) in.readobject(); (int = 0; < database.length; i++){ mylist.add(database[i]); } mylist.add((t) "\n"); mylist.add((t) "\tstudents:"); objectinputstream in1 = new objectinputstream(new fileinputstream("students.bin")); database = (t[]) in1.readobject(); (int = 0; < database.length; i++){ mylist.add(database[i]); } } } public class student implements serializable, comparable{ private string name, id, address; private double gpa; public student(string name, string id, double gpa){ this.name = name; this.id = id; this.gpa = gpa; } public int compareto(object object){ student student = (student ) object; if(this.gpa < student.getgpa()) return -1; else if(this.gpa > student.getgpa()) return 1; else return 0; } public string getname(){ return name;} public string getid(){ return id;} public double getgpa(){ return gpa;} public string tostring(){ return (string.format("%16s%10.4s%8s", name, id, gpa));} }
assuming mean within databaseaccess, in theory, don't.
now, use following, horrible idea , absolutely reeks of bad design (no offense meant - don't want give impression code @ okay or should use - technically possible):
(t t : mylist) { if (t instanceof student) { student student = (student) t; student.getgpa(); } else if (t instanceof food) { ... } }
as far databaseaccess concerned, it's not student. it's random object of type t know nothing about. if can't create common interface between student , food want, have ask why databaseaccess needs know specifics of classes , figure out design should separate things more sanely.
are doing custom printing? maybe formatting should done within student/food class.
are you, e.g. processing user input , manipulating data objects in database? separate concerns of database access , data manipulation. changing gpa shouldn't require know whether data being stored in objectoutputstream or oracle database. so, have databaseaccess deal database, , define other class works databaseaccess<student>
through defined interface, , have handle student-specific manipulation.
without knowing precisely you're trying do, it's hard give solid advice beyond: if think need you're asking, might want step , think if there might better way approach problem don't.