Java : Getter /setter for Arraylist<Object> - java

so i have :
ArrayList<data> mi = new ArrayList<data>();
i have a Query which do following :
while (rs.next()) {
mi.add(new users());
mi.get(i).name= rs.getString("name");
mi.get(i).pass= rs.getString("pass");
}
It works but i want it with Getter/setters like :
mi.get(i).setname( rs.getString("name"));
Edit : Misspelling i had it so
Why cant i call the methode?

Use
mi.get(i).setname(rs.getString("name"));

Your users class should have a public setname(String name) method, which sets the name field of user class
then, mi.get(i).setname(rs.getString("name")); will work

Because it is java. You cannot have such assignment
setname() = rs.getString("name")
It does not make sense. You shall set it as argument:
object.setName(rs.getString("name"))
Also please respect java naming conventions: Class has CamelCase, methods start with lower first character and then continue with camel case as well: setUserName

with
mi.get(i).setname()
you call the method setname(). The result (if any) is not a variable name and you cannot assign a value to it.
If your class has a method setname(String s) then use it as usual in Java:
mi.get(i).setname(rs.getString("name"))

I would recommend using the below approach
while (rs.next()) {
Users user = new Users();
user.setName(rs.getString("name"));
user.setPass(rs.getString("pass"));
mi.add(user);
}
Seems neater to set the values in your object and then adding them to the list.

Related

Android arraylist into Textview error

I tried to set value in TextView using my array logic.
Problem:
Instead of my actual value it might set address of string in
textview. I'm guessing this issue is simple, possibly not specifying .toString()?
Value that is being outputted:
com.android.carModel.Car#eacea24f
My code:
StringBuilder builder = new StringBuilder();
val = carDAO.carOutput(carId);
textbx.setText("");
for (Car details : val){
builder.append(details + "\n");
}
textbx.setText(builder.toString());
Your code is actually append someObjectClassname#hashcodenumber i.e com.android.carModel.Car#eacea24f in your case to stringBuilder. To get the desired output you need to do something like this.
`builder.append(details.getName() /*or anything*/ + "\n")`
Do you have access to the Car class? If so, add this method:
public String toString() {
return carName;
}
Replace carName with whatever you want to display. This toString() method is part of the Object class that all classes extend, and when overridden, it will change what something like a List will display.

Use SELECT NEW CONSTRUCTOR with parameter not from tables

I'm using something like this now in my HQL:
"SELECT NEW com.somepackage.dto.SomeClass(myObj) "
But now I want to add a boolean parameter to constructor.
I've added it to my DAO method with HQL and to constructor of my dto object:
"SELECT NEW com.somepackage.dto.SomeClass(myObj, :param) "
...
.setParameter("param", param)
After adding parameter I got an exception:
Unable to locate appropriate constructor on class
Is there a way to add param to constructor? Or I was made something wrong?
Thx for your replies and sorry for my English.
Update
(Simple copy of my SomeClass):
public class SomeClass extends SomeClassParent {
private final String someParam;
private final List<MyObject> myObjects;
public SomeClass(MyObject myObject) {
super(myObject.getFirstField,
myObject.getSecondField, ...);
this.someParam = myObject.getSomeParamValue();
StringBuilder bodyBuilder = new StringBuilder();
...
I want it to be
public SomeClass(MyObject myObject, boolean myBoolean) {
I don't know exactly what was the problem with boolean, but now I'm using String parameter against boolean and use it like this:
"SELECT NEW com.somepackage.dto.SomeClass(myObj, '" + param + "') "...
setParameter doesn't want to work with String, because it requires quotes to be result string like this:
"SELECT NEW com.somepackage.dto.SomeClass(myObj, 'Some string') "...
against
"SELECT NEW com.somepackage.dto.SomeClass(myObj, Some string) "...
Ok, what it wasn't clear to me was if you had the SomeClass definition, you can define as many constructors as you want as long as they have different types, or quantities of parameters passed by.
It can be see as a kind of override (although it is not!)
It's up to you to define it, and do whatever you want with that Boolean, in fact you can copy and paste the original constructor (just leave that one there, don't erase it) with the Boolean's addition and it would be as valid as the previous one.
I'm pretty sure that your problem is with the boolean field. I worked with Hibernate HQL and I had a similar problem with a field. At the end I realized that I have to use nullable files for every field.
So, I think this problem could be solved turning boolean primitive field into Boolean Object class.
I'm having a similar problem with constructing a result entity using a query parameter as a constructor argument - like "select new com.example.ResultType(t.id, ?1) from Table t where ...". It seems such bare query params just get ignored when looking for constructors - in that example it would look for a constructor that takes a single argument matching t.id.
The only work-around I've found so far is to wrap the parameter with a cast (or some other non-trivial expression), e.g. "select new com.example.ResultType(t.id, cast(?1 as string)) ...".

Calling the class in java, using the name of a class from a string

Is there any easy way to achieve this.
Let's say I have an array of string with the name of POJO's in there and I"m trying to print all the list of attributes, is there any way to achieve this easily?\
String [] nameofClass;
for(String name:nameofClass)
name.class.getDeclaredFields();
Thanks
Class.forName(name).getDeclaredFields() within your for loop is probably what you're looking for.
Note that name should be the full path of the class, i.e. not only TheClass but the.package.to.TheClass.
Yes you can. See the example given below:
String [] nameofClass = {"java.lang.Object","java.lang.Thread"};//Give complete path of the class
try{
for(String name : nameofClass)
{
Class cl = Class.forName(name);
System.out.println(cl);
System.out.println("\t"+java.util.Arrays.toString(cl.getDeclaredFields()));
}
}catch(Exception ex){System.out.println(ex);}

Dynamic variable names in Java so each new object has separate name

How can I do such a thing?
String N = jTextField0.getText();
MyClass (N) = new Myclass();
Is it even possibe?
Or as my question's explains, how can I just make a method to create a new object of my specified class just with a different name each time I call it.
I really searched everywhere with no luck.
Thanks in Advance
P.S.
I wish you guys can excuse me for not being clear enough, Just to say it as it is, I made a textfield to get the name of someone who wants to make an account, and I made a class named "Customer". and a button named "Add". Now I want every time "Add" is clicked, compiler take what is in my textfield and make an object of the class "Customer" named with what it took from the textfield
It was too hard to read it in comments so I updated my question again, so sorry.
I'm stuck so bad. I suppose my problem is that I didn't "understand" what you did and only tried to copy it. This is what I wrote:
private void AddB0MouseClicked(java.awt.event.MouseEvent evt) {
String name = NameT0.getText();
Customer instance = new Customer(Name);
Customer.customers.add(instance);
and this is my Customer class:
public class Customer{
String name;
public Customer(String name){
this.name = name;
}
public String getName(){
return name;
}
static ArrayList<Customer> customers = new ArrayList<Customer>();
Variable names must be determined at compile time, they are not even part of the generated code. So there is no way to do that.
If you want to be able to give your objects names, you can use
Map<String, MyClass> map = new HashMap<>();
Add objects to the map like this (e.g):
map.put(userInput, new MyClass());
and retrieve objects like this:
MyClass mc = map.get(userInput);
I'm not entirely sure what you mean by...
how can I just make a method to create a new object of my specified
class just with a different name each time I call it
...but if I'm interpreting you correctly, I believe what you're trying to do as make MyClass accept a constructor parameter. You can do:
public class MyClass {
private String name;
public MyClass(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Then to create a new instance of MyClass, do:
String name = jTextField0.getText();
MyClass instance = new MyClass(name);
instance.getName(); // returns the name it was given
EDIT
Since you've added clarifications in the comments since I first answered this question, I thought I would update the answer to portray more of the functionality that you're looking for.
To keep track of the MyClass instances, you can add them to an ArrayList. ArrayList objects can be instantiated as follows:
ArrayList<MyClass> customers = new ArrayList<MyClass>();
Then for each MyClass instance you wish to add, do the following:
customers.add(instance);
Note that the ArrayList should not be reinstantiated for each instance that you wish to add; you should only instantiate the ArrayList once.

How to use ArrayList to find a name in a register

I am currently working on the following question:
Assume a class Name has attributes "surname" and "firstname" stored as Strings. Let "regist" be a list of Name with declaration:
ArrayList<Name> regist = new ArrayList<Name>();
Assuming that "regist" is populated, implement the method below that finds a name in the list with the given surname, or returns null if no
matching name exists in the list. (You may write Java code or a mix of
Java and pseudo-code).
public Name find(String surname)
{
//... to do ...
}
The answer that I have been able to come with so far is:
public Name find (String surname)
{
this.surname = surname;
return null;
}
public Name()
{
surname = " ";
}
After that, I am stuck from here, if anyone can show me how to complete this code then your help would be truly appreciated, thanks in advance.
(I would be able to test this code properly if I am able to complete it properly).
You have to loop over the items in regList and return the Name object with the given surname. Your current code for find is incorrect -- the find method is not in the name class and (or should not) be allowed to change variables inside a Name object directly.
At any rate, the solution is:
public Name find(String surname)
{
for(Name obj : regList)
{
// Check the object's surname with the given one
// Should check if obj is null
// Must use .equals to compare strings.
if(obj.surname.equals(surname))
return obj;
}
// Not found
return null;
}
You're going to need to loop through regist and test if the surname matches the parameter... If the loop exits without finding a match then return null.
Do you mean something along the lines of:
public Name find (String surname)
{
// loop all names in regist
for(Name n : regist)
{
// find the Name object with matching surname
if(n.getSurname().equals(surname))
{
return n;
}
}
return null;
}
The ArrayList you declared in
ArrayList<Name> regist = new ArrayList<Name>();
may already have the surename you want to find. To find it you have to do the following in sudo code:
Find how many names is stored in regist, then check every name from place 0 to the last place in regist. If it is the same, then return the first and surname. Remember that both first and surname is added to regist, and you should only test for the surename and return the both first and surename if surename is correct.

Categories

Resources