making a little mini blog application, just setting up the places to hold the data. I have 3 classes one for the post one for the user and one for the test, which I named Blog. when I try to call the getName(); method in the Blog class it won't run it keeps saying it needs a string, but I made an array of user objects, and input a string for the userName spot, and it still isn't working.
public class Blog
{
public static void main(String []args)
{
User[] userList = new User[3];
userList[0] = new User("what.com", "TheLegionCrab", "Jake Parham", "jparham#gmail.com");
userList[1] = new User("huh.com", "RaggleFraggle", "Brett Hawkins", "bhawkins#gmail.com");
userList[2] = new User("buh.com", "SeanBeast", "Sean Sweeney", "ssweeney#gmail.com");
for(int counter = 0; counter<userList.length; counter++)
{
User.getName();
}
}
}
public class User
{
private String url;
private String userName;
private String realName;
private String email;
public User(String url, String userName, String realName, String email)
{
this.url = url;
this.userName = userName;
this.realName = realName;
this.email = email;
}
public void getName(String userName)
{
System.out.println(userName);
}
}
public void getName(String userName)
{
System.out.println(userName);
}
Here your function require a String. That is why it need string to run. If you want to print the userName of the current User object in your loop then use this.
public void getName()
{
System.out.println(this.userName);
}
This refer to current User object in your loop.
Now back to your loop.
for(int counter = 0; counter<userList.length; counter++)
{
User.getName();
}
You use User class meanwhile you create variable as
User[] userList = new User[3];
To print from your var, you should use the var.
for(int counter = 0; counter<userList.length; counter++)
{
userList[counter].getName();
}
You need to access a User instance from your userList array (or get an instance some other way) to call the method on (and either assign it to a variable and use it or just print it). In Java, array access is performed with []. Something like
for (int counter = 0; counter < userList.length; counter++)
{
System.out.println(userList[counter].getName());
}
You could also you an enhanced for loop (for-each loop) like
for (User user : userList) {
System.out.println(user.getName());
}
Also, I don't think getName should be shadowing the class name field. You wanted something like,
public void getName()
{
System.out.println(this.userName);
}
or following the Java practice of returning the value in a getter (and to fix my examples above)
public String getName()
{
return this.userName;
}
That's because you specified that the getName method in the User class takes a String as the argument. You did that here:
public void getName(String userName)
{
System.out.println(userName);
}
So it's working exactly they way you have told it to.
But really, you want "setName()" to take a String arg, and "getName()" to take no arg. It should look like this:
public void setName(String new_userName)
{
username = new_userName;
}
public void getName()
{
System.out.println(userName);
}
But even then, I'd say that your method names are a bit ambiguous: should I use "getName" to get the username, or to get the realName?
(did you spot the error?)
It looks like what you want is to print the name of the user instance instead of the parameter to the getName method. Try this defining the method like this:
public void getName()
{
System.out.println(this.userName);
}
and in the main method:
User[] userList = new User[3];
userList[0] = new User("what.com", "TheLegionCrab", "Jake Parham", "jparham#gmail.com");
userList[1] = new User("huh.com", "RaggleFraggle", "Brett Hawkins", "bhawkins#gmail.com");
userList[2] = new User("buh.com", "SeanBeast", "Sean Sweeney", "ssweeney#gmail.com");
for(int counter = 0; counter<userList.length; counter++)
{
userList[counter].getName();
}
Issues:
a) Calling getName() without any object i.e as a static function. Instead use the objects created and call it as:
userList[counter].getName();
b)Creating User objects with the name (in constructor) and also calling getName with argument i.e userName. This is wrong/not needed. When you created the object, you have already informed the object about the userName. So have a clean getter without any argument.
getName()
The code:
public class Blog
{
public static void main(String []args)
{
User[] userList = new User[3];
userList[0] = new User("what.com", "TheLegionCrab", "Jake Parham", "jparham#gmail.com");
userList[1] = new User("huh.com", "RaggleFraggle", "Brett Hawkins", "bhawkins#gmail.com");
userList[2] = new User("buh.com", "SeanBeast", "Sean Sweeney", "ssweeney#gmail.com");
for(int counter = 0; counter<userList.length; counter++)
{
userList[counter].getName(); # Correct this to use the created objects.
}
}
}
public class User
{
private String url;
private String userName;
private String realName;
private String email;
public User(String url, String userName, String realName, String email)
{
this.url = url;
this.userName = userName;
this.realName = realName;
this.email = email;
}
public void getName() #Remove the argument.
{
System.out.println(this.userName);
}
}
You have to make the object of the User class before calling else your User class should be static to call it direct.
for(int counter = 0; counter<userList.length; counter++)
{ User obj = new User();
obj.getName();
}
else
public static User
{
public User(String url, String userName, String realName, String email)
{
this.url = url;
this.userName = userName;
this.realName = realName;
this.email = email;
}
public void getName(String userName)
{
System.out.println(userName);
}
}
Related
Sailor class
public class Sailor {
private String name;
private String email;
public Sailor(String name, String email) {
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Crew class
import java.util.ArrayList;
public class Crew {
private ArrayList<Sailor> sailorList = new ArrayList<>();
public Crew() {
}
public void addCrewMember(Sailor sailor) {
sailorList.add(sailor);
}
public String toString() {
String str = "";
for(int i = 0; i < sailorList.size(); i++) {
str = sailorList.get(i).getName() + sailorList.get(i).getEmail();
}
return str;
}
}
Main program
public class ObjectsSailorProgram {
public static void main(String[] args) {
Sailor firstSailor = new Sailor("Frank", "frank#mail.com");
Sailor secondSailor = new Sailor("Susan", "susan#mail.com");
Sailor thirdSailor = new Sailor("John", "john#sailors.com");
Sailor fourthSailor = new Sailor("Ann", "ann#sailors.com");
Crew firstCrew = new Crew();
Crew secondCrew = new Crew();
firstCrew.addCrewMember(firstSailor);
firstCrew.addCrewMember(secondSailor);
firstCrew.addCrewMember(fourthSailor);
secondCrew.addCrewMember(thirdSailor);
secondCrew.addCrewMember(secondSailor);
System.out.println("=== First crew ===\n" + firstCrew);
System.out.println("=== Second crew ===\n" + secondCrew);
secondSailor.setEmail("Susan#sailors.com");
System.out.println("=== Second crew ===\n" + secondCrew);
}
}
I am having trouble printing the crews and I'm not sure if the addCrewMember is correct.
I've tried reading other similar posts but i haven't been able to use the solutions here. So i need help with the addCrewMember and toString methods
You aren't setting the variables neither in constructor nor by calling setters in your main.
You can change the constructor as below:
public Sailor(String name, String email) {
this.name = name;
this.email = email;
}
In your toString() method, you're overwriting the str. Use StringBuilder to append strings into the resulting string. You can modify your toString() method as follows:
public String toString() {
StringBuilder str = new StringBuilder();
for(int i = 0; i < sailorList.size(); i++) {
str.append(i+1)
.append(". ")
.append(sailorList.get(i).getName())
.append(" ")
.append(sailorList.get(i).getEmail())
.append("\n");
}
return str.toString();
}
And your program will give the output:
=== First crew ===
1. Frank frank#mail.com
2. Susan susan#mail.com
3. Ann ann#sailors.com
=== Second crew ===
1. John john#sailors.com
2. Susan susan#mail.com
=== Second crew ===
1. John john#sailors.com
2. Susan Susan#sailors.com
0> sailor's constructor is wrong-> you're not initializing the data
public Sailor(String name, String email) {
setEmail(email); //or this.email=email;
this.name=name; //you may make a setter also for this
}
1> private ArrayList<Sailor> sailorList = new ArrayList<Sailor>();
2> the to-string is also wrong: it prints just the last sailor, use += instead of =
str +=" "+ sailorList.get(i).getName() + sailorList.get(i).getEmail();
This is just personal taste: I prefer "for-each" syntax.
for(Sailor s: sailorList){
out += s.getName()+" "+s.getEmail();
}
As others have noted, you are not assigning the values in your Sailor constructor so do that. You should also add any missing get/set methods.
public Sailor(String name, String email) {
this.name = name;
this.email = email;
}
The addCrewMember(Sailor) method in Crew looks correct but your toString() method is flawed.
You are trying to build a String but you are re-assigning it on each iteration rather then concatenating elements on each iteration.
Except in very simple cases, you should avoid String concatenation when compose Strings.
The code is pushing all of the elements together with no separation which means you will have an unreadable blob of characters (e.g. bobsmithbsmith#boat.comsamsmithssmith#boat.com)
I would suggest that you write a toString() in Sailor class. This example separates the elements of Sailor by commas and wraps the entire entity in curly braces (e.g. "{Sam Smith, ssmith#boat.com}"). Note the use of String.format(..) rather than concatenation.
public class Sailor {
... stuff ...
#Override public String toString() {
return String.format("{%s, %s}", name, email);
}
}
The Crew.toString() method can employ this to compose its String. The following makes use of the StringJoiner class to compose a comma-separated list of elements wrapped in square braces to represent the crew members (e.g. "[{Al Almond, aalmond#boat.com},{Bob Bobson, bbobson#boat.com}]");
public class Crew {
... stuff ...
#Override public String toString() {
StringJoiner sj = new StringJoiner(",", "[", "]");
for (Sailor s : sailorList) {
sj.add(s.toString()); // Sailor.toString() is explicitly invoked here but you could remove that call and it should still be invoked implicitly
}
return sj.toString();
}
}
Hi I'm working on an android studio project using global arrays,
I can read from the global arrays fine, and have no problem writing
to the global integers ,But i cannot figure out how to set the global
array from code, this is the important parts of the project:
added this under application tag in the android manifest xml:
android:name=".Globals"
java class Globals:
import android.app.Application;
public class Globals extends Application {
public int empnum=13;
public int getData3() {
return empnum;
}
public void setData3(int empnum) {
this.empnum = empnum;
}
public String[] passw = {"0123","0123","0123","0123","0123","0123","0123","0123","0123","0123","0123","0123","0123"};
public String[] getData4() {
return passw;
}
public void setData4(String[] passw) {
this.passw = passw;
}
public int login=0;
public int getData5() {
return login;
}
public void setData5(int login) {
this.login = login;
}
public String[] empname = {"Name1","Name2","Name3","Name4","Name5","Name6","Name7","Name8","Name9","Name10","Name11","Name12","Name13","Not logged in"};
public String[] getData6() {
return empname;
}
public void setData6(String[] empname) {
this.empname = empname;
}
Here is the block of code I'm having trouble with
inner class of java class TimeIn:
final Globals g = (Globals) getApplication();
final String[] empname = g.getData6();
final String[] passw = g.getData4();
public void onClick(View v) {
i = 0;
String empname = edit2.getText().toString();
int getemn = Integer.parseInt(edit.getText().toString());
if (i == 0 && h == 0) {
g.setData3(getemn);
g.setData6(String[getemn], empname); // This one line right here won't compile, I have tried different combinations but have had 0 luck
i = 1;
h = 1;
}
}
I have no problems getting and using a String array, this is how it works to get
an array value and compare it to a string:
public void onClick(View v) {
i = 0;
String getemp = edit2.getText().toString();
int getemn = Integer.parseInt(edit.getText().toString());
if (i == 0 && getemp.equals(passw[getemn])) { // All of this works perfectly
g.setData3(getemn);
g.setData5(0);
tfone.setText("Empoyee " + getemn);
tftwo.setText("Logged in");
i = 1;
}
if (i == 0 && getemp != (passw[getemn])) {
tfone.setText("No matches found");
edit2.setText("Not logged in");
i = 1;
}
}
So I know this line of code is wrong:
g.setData6(String[getemn], empname);
but for
the life of me I can't figure out how it should be written, the only error hint is I
get from hovering over the line-
array type expected; found 'java.lang.String'
Anyone know what I'm doing wrong?
In Global class, you declare the method with one parameter
public void setData6(String[] empname) {
this.empname = empname;
}
but when you call, you put 2 parameters g.setData6(String[getemn], empname);
You should remove one parameter
or add another method with 2 parameters in Globals class
Also
You are wrong in here
...
String empname = edit2.getText().toString();
int getemn = Integer.parseInt(edit.getText().toString());
...
g.setData6(String[getemn], empname); // This one line right here won't compile, I have tried different combinations but have had 0 luck
The setData6 function now require 2 parameters, one is String array and the other is String
but the way you put the String array to the function is wrong
Here is a simple example that show how to pass the String array to function
public class Test {
public static void setData6(String[] empnameList, String empname) { // with the `String array` you should declare the variable name like `empnameList` or `arrEmpname` NOT `empname` because `empname` make confusing when you read code
this.empnameList = empnameList;
this.empname = empname;
}
public static void main(String[] args) {
String[] strArray = new String[]{"Name1","Name2","Name2"};
String empName = "Na";
setData6(strArray,empName); // call method with 2 parameters here
}
}
Hope this help
Solved!! it turns out I had to modify my setter part of my Globals class, so this first part (the getter method) in the Globals class is correct:
public String[] compname = {"Manager's company", "Company2", "Company3", "Company4", "Company5", "Company6", "Company7", "Company8", "Company9", "Company10", "Company11", "Company12", "Company13", "Not punched in"};
public String[] getData7() {
return compname;
}
I had to change the getter part of my Globals class to this:
public int setcmpn = 0; // <-- Edited, this should equal some integer value
public void setData7(int setcmpn, String compname) { // removed [] from 2nd argument
this.setcmpn = setcmpn;
this.compname[setcmpn] = compname; // added in [] after array's name and fill it with the first argument from setData7 method
}
And to set the value of the desired index from any class just use:
Globals g = (Globals) getApplication();
g.setData7(getemn, getemp);
where getemn is an integer and getemp is a string.
Im try to insert data into Database using ArrayList.there is a Erro msg.
That is my Custmer.class method. this is what i got from when i going to pass ArrayList into another class.
incompatible types: ArrayList<String> cannot be converted to ArrayList<Inquiries>
I want to know how to do this using correct Using OOP concept
public void passingMsg(ArrayList<Inquiries> arrlist){
try {
System.out.println("Method "+arrlist);
String sq = "INSERT INTO Inquiries (name,mail,tp,msg)VALUES(?,?,?)";
PreparedStatement pr = con.prepareStatement(sq);
for(int i=0;i<arrlist.size();i++){
pr.setString(1,arrlist.get(i).getName());
pr.setString(2,arrlist.get(i).getMail());
pr.setString(3,arrlist.get(i).getTp());
pr.setString(4,arrlist.get(i).getMsg());
}
pr.executeQuery();//executeBatch();
} catch (SQLException ex) {
}
}
and this is how i get values from user
String name = txtName.getText();
String mail = txtEmail.getText();
String tp = txtTp.getText();
String msg = txtMsg.getText();
ArrayList<String> arrInq = new ArrayList<String>();
arrInq.add(name);
arrInq.add(mail);
arrInq.add(tp);
arrInq.add(msg);
Custmer c =new Custmer();
if( c.passingMsg(arrInq)){
try {
JOptionPane.showMessageDialog(this, "Successs!!");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Unsuccesss!!");
e.printStackTrace();
}
}
and this is my Inquiries.class :
public class Inquiries {
private String name;
private String mail;
private String tp;
private String msg;
public Inquiries(String name,String mail,String tp,String msg){
this.name = name;
this.mail = mail;
this.tp = tp;
this.msg = msg;
}
//
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getTp() {
return tp;
}
public void setTp(String tp) {
this.tp = tp;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
Can Some one please explain whats wrong with this. please ?
Reason For Error
This was simply telling you that your types were incompatible for the operation you were trying to perform. In your passingMsg() method, you have its header as: public void passingMsg(ArrayList<Inquiries> arrlist). However, inside your "how i get values from user" area, which I will now refer to as "2nd Snippet", you have your method call declared as: if( c.passingMsg(arrInq)). This means that you are implying that your parameter being passed, arrInq in this case, is of the type ArrayList<Inquiries>, but it's not. It's being initialized in your 2nd Snippet as: ArrayList<String> arrInq = new ArrayList<String>();
Simple Fix
I take no responsibility for this code; use at your own risk. To fix this, you would want to change that entire 2nd Snippet to something similar to the following:
String name = txtName.getText();
String mail = txtEmail.getText();
String tp = txtTp.getText();
String msg = txtMsg.getText();
ArrayList<Inquiries> arrInq = new ArrayList<Inquiries>();
arrInq.add(new Inquiries(name, mail, tp, msg));
Custmer c = new Custmer();
try {
c.passingMsg(arrInq);
JOptionPane.showMessageDialog(this, "Successs!!");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Unsuccesss!!");
e.printStackTrace();
}
You would also want to change the method header to either return a boolean, or fix it up a little bit to actually throw the exception. Such as:
public void passingMsg(ArrayList<Inquiries> arrlist) {
System.out.println("Method " + arrlist);
String sq = "INSERT INTO Inquiries(name,mail,tp,msg) VALUES(?,?,?)";
PreparedStatement pr = con.prepareStatement(sq);
for (Inquiries inquiries : arrlist) {
pr.setString(1, inquiries.getName());
pr.setString(2, inquiries.getMail());
pr.setString(3, inquiries.getTp());
pr.setString(4, inquiries.getMsg());
}
pr.executeQuery();//executeBatch();
}
Let's talk in O-O-P way.
Here Inquiries is your model, model is nothing but simple class that has instance members and public methods to get and set value of model's instance variable.
Generally we put all database related operations code in their respective models.
e.g. I have model "Model" which typically maps to database table say it as "TableModel" ,I would do something like this:
public class Model{
private int id;
private String attr;
//other properties of the model
public int getId(){
return id;
}
public void setId(int id){
this.id=id;
}
//other getters and setters
//here we write methods to performs database operations
public void save(){
//use "this" to get properties of object
//logic to save to this object in database table TableModel as record
}
public void delete(int id){
//logic to delete this object i.e. from database table TableModel
}
public Model get(int id){
//retrieve record from table TableModel with this id
}
//other methods to get data from database.
}
Now question is how I can use this in some another class. Let's say I have list of Model objects and I wish to insert them in to database.I will do it something like this:
public class AnotherClass{
public void someMethod(){
//create list of models objects e.g. get them from user interface
ArrayList<Model> models=new ArrayList<>();
for(int i=0;i<3;i++){
Model model=new Model();
model.setId(i);
model.setAttr("attr"+i);
models.add(model);
}
SomeOtherClass obj=new SomeOtherClass();
obj.insert(models);
}
}
public class SomeOtherClass{
//other code above.....
//my method that inserts each Model object in database
//Note: this is sample method , you should do it in optimized way
// e.g. batch insert
public void insert(ArrayList<Model> models){
for(Model myModel:models){
myModel.save();
}
}
//other code below.....
}
You are using the wrong type parameter for the ArrayList. Instead of ArrayList<String> you need ArrayList<Inquiries>. To fix the problem, you should remove this code ...
ArrayList<String> arrInq = new ArrayList<String>();
arrInq.add(name);
arrInq.add(mail);
arrInq.add(tp);
arrInq.add(msg);
... and replace it with this code:
ArrayList<Inquiries> arrInq = new ArrayList<Inquiries>();
arrInq.add(new Inquiries(name, mail, tp, msg));
I am working on a project ( I had a problem yesterday and so many people helped me!) so I decided to ask for help again.
My code has 3 classes. ProjectMain,Students,Classroom. I created an array of Classroom objects. Right now I have 3 Classroom objects. But I have to assign student objects to these Classroom objects. For example : classarray[0] is an object from Classroom class and studentobject.get(0) , studentobject.get(1) ... will be students objects inside classarray[0] object. But I have failed on this while coding. Here are my classes :
public class Classroom
{
private String classname;
private String word[] = null;
protected ArrayList<Students> studentobject = new ArrayList<Students>(10);
public String[] getWord()
{
return word;
}
public void setWord(String[] word)
{
this.word = word;
}
public ArrayList<Students> getStudentobject()
{
return studentobject;
}
public void setStudentobject(ArrayList<Students> studentobject)
{
this.studentobject = studentobject;
}
public String getClassname()
{
return classname;
}
public void setClassname(String classname)
{
this.classname = classname;
}
public void classroomreader(String filename)
{
// This method gets the name of Classroom
File text = new File("C:/Users/Lab/Desktop/classlists/" + filename
+ ".txt");
Scanner scan;
try
{
scan = new Scanner(text);
String line = scan.nextLine();
word = line.split("\t");
line = scan.nextLine();
word = line.split("\t");
} catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
}
}
This is my student class :
public class Students extends Classroom
{
private String name,id;
private int age;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
And my main class :
public class ProjectMain
{
public static void main(String[] args)
{
Classroom[] classarray = new Classroom[3];
//I got 3 Classroom objects here
classarray[0]=new Classroom();
classarray[1]=new Classroom();
classarray[2]=new Classroom();
classarray[0].classroomreader("class1");
classarray[0].studentobject.get(0).setName(classarray[0].getWord()[1]);
//The problem is in here. When my code comes to the line above,
// at java.util.ArrayList.rangeCheck(Unknown Source) error comes out.
// I tried to get first object in studentobject Arraylist, and tried to set it's name
// to the variable which my text reader reads.
How can I write what I have in my mind?
Your classroomreader method reads the file but don't do much of it... maybe you want to create some instance of Students within it.
scan = new Scanner(text);
String line = scan.nextLine();
word = line.split("\t"); // won't be used
line = scan.nextLine();
word = line.split("\t"); // erased here
There you only have the last line (split) of the file in word attribute.
When creating Classroom instance studentobject list is created empty and it stays that way so you can't access first (or any) object in it.
To populate your list you may add to Classroom method like this:
public void addStudent(Student s)
{
studentobject.add(s);
}
classroom contains the following field declaration
String word[] = null;
the main class, incl the classroomreader does not set a value to this field. Yet you are going to invoke
classarray[0].getWord()[1]
which then must fail.
tip: don't use expressions like this, which can be found in your main class (at least not in early stages of development, or learning)
classarray[0].studentobject.get(0).setName(classarray[0].getWord()[1]);
resolve into variables and several steps. Compilers are smart enough to produce the same code if the context is not disturbed, ie the long expression is resolved into a single block.
Never forget that the purpose of programming languages is to make programs readable for humans. :) Code with abbreviations or "tricks" simply shows some philodoxical attitude (imho)
I have a HashMap that look something like this-
HashMap<String, TableConnectionInfo> tableList
which means it's value is a Class TableConnectionInfo which looks something like this-
public class TableConnectionInfo {
public String url;
public String user;
public String password;
public String driver;
public String suffix;
public String sql;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
}
So Suppose, If I have two values in the above HashMap. That means, I need to make two different connections to two different database. And suppose if that map has three values, then I need to make three different connections to three different database.
In the main thread, I am populating the above map by reading it from the properties file like this and after that this map won't get modified.
for (String arg : databaseNames) {
TableConnectionInfo ci = new TableConnectionInfo();
String url = prop.getProperty(arg + ".url");
String user = prop.getProperty(arg + ".user");
String password = prop.getProperty(arg + ".password");
String driver = prop.getProperty(arg + ".driver");
String suffix = prop.getProperty(arg + ".suffix");
String sql = prop.getProperty(arg + ".sql");
ci.setUrl(url);
ci.setDriver(driver);
ci.setPassword(password);
ci.setSql(sql);
ci.setSuffix(suffix);
ci.setUser(user);
tableList.put(arg, ci);
}
Now I am passing this tableList map to various threads like this and it won't be modified (by making set calls) by any thread. Each thread will be using get method to get the required method.
for (int i = 0; i< 1000; i++) {
service.submit(new Task(tableList));
}
So in the run method I need to make different conenctions basis on the tableList size. So if tableList size is two, that means I need to make two different connections, callableStatements and methods to two different database.
Question:-
So is there any better way as compared to way I am doing in my run method to create different connections to database basis on tableList size ?
Below is my Task class that impelements Runnable Interface
class Task implements Runnable {
private Connection[] dbConnection = null;
private CallableStatement[] callableStatement = null;
private ArrayList<Method> methods[] = null;
private final HashMap<String, TableConnectionInfo> tableLists;
public Task(HashMap<String, TableConnectionInfo> tableList) {
this.tableLists = tableList;
}
#Override
public void run() {
try {
int j = 0;
dbConnection = new Connection[tableLists.size()];
callableStatement = new CallableStatement[tableLists.size()];
methods = new ArrayList[tableLists.size()];
for (TableConnectionInfo ci : tableLists.values()) {
dbConnection[j] = getDBConnection(ci.getUrl(), ci.getUser(), ci.getPassword(), ci.getDriver());
callableStatement[j] = dbConnection[j].prepareCall(ci.getSql());
methods[j] = getRequiredMethods(ci.getSuffix());
j++;
}
}
}
}
Make a connection to that database-
private Connection getDBConnection(String url, String username, String password, String driver) {
Connection dbConnection = null;
try {
Class.forName(driver);
dbConnection = DriverManager.getConnection(url, username, password);
}
return dbConnection;
}
Just to add here getRequiredMethods will get all the methodNames of a particular table. So suppose if tableList size is 1 then we will be having only one connection to that database so getRequiredMethods will get all the methods for that table1 and store it in a ArrayList. But suppose if tableList size is 2 then we will be having two different connections to two different database so that is the reason I made methods as an array so that it can hold methods for table 1 and methods for table 2.
Ok, I'm still not sure how the Task is meant to use the data it's getting. But, I would move the getConnection, getCallableStatement and getMethods() functions to methods on the TableConnectionInfo. You can simply create a Collection of TableConnectionInfo (initialised as you already have, storing in an ArrayList). Then the Runnable simply iterates through the TableConnectionInfo.
public class TableConnectionInfo {
private String url;
private String user;
private String password;
private String driver;
private String suffix;
private String sql;
private Connection connection;
<snip... getters and setters for the properties>
public Connection getConnection() {
// TODO create and return a connection
if (connection == null) {
// create the connection
}
return connection;
}
public CallableStatement getCallableStatement() {
// get the callable statement
return null;
}
public Collection<Method> getMethods() {
// Get the Methods
return null;
}
}
public class TableTask implements Runnable {
private Collection<TableConnectionInfo> tables;
public TableTask(Collection<TableConnectionInfo> tables) {
this.tables = tables;
}
#Override
public void run() {
for (TableConnectionInfo table : tables) {
// do something with table.getConnection(), or table.getCallableStatement()
// and/or table.getMethods()
}
}
}