Java Arraylist change affect other variables - java

I am using java fx, nothing fancy in the code below, and catching the text field's focusedProperty to overwrite the newly entered value below. The code below changes a person's name that is entered in the textfield and when user clicks on cancel button it will put the old name back into the textfield. But for some reason a magic happens and whenever I set the person's name it overwrites the field in the cancelPerson variable. Could not figure out why this would happen? I get the cancelPerson from persons list before I set the new value. So how come changes in the persons list can affect an independent variable. Any idea why this would occur? Thanks.
private ObservableList<Person> persons;
private Person person;
private Person cancelPerson;
personName.focusedProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue) {
final int index = personIdCombo.getSelectionModel().getSelectedIndex();
cancelPerson = persons.get(index);
final Person person = persons.get(index);
person.setName(personName.getText());
persons.set(index, person);
}
}
);
class Person{
private final StringProperty name;
public Person() {
this.name = new SimpleStringProperty("testName");
}
public SystemParams(Person person) {
this.name = person.name;
}
}

Jim Garrison's answer (suggesting the copy constructor) is correct; I
just wanted to add another answer to give a helpful way of thinking
about references in Java.
I found it helpful to think of an = assignment as a REFERS TO assignment. So, cancelPersons = persons.get(index); is basically saying:
cancelPerson REFERS TO persons.get(index);
Now, where your second line says final Person person = persons.get(index);, think of it as
final Person person REFERS TO persons.get(index);
See how they both REFER TO the same persons.get(index)? Now, whether you use cancelPerson or just person, Java is pointing back to the same overall object, not different ones.
Unless you have a new keyword somewhere, you are not actually creating a new object.

This is because person and cancelPerson are references and when you do
cancelPerson = persons.get(index);
final Person person = persons.get(index);
You end up with both variables pointing to the same object.
If you want to save a copy of person you have to do a "deep copy", that is create a new Person and copy the contents to the new object. This is usually done with what is referred to as a "copy constructor"
class Person {
public Person() { ... the no-arg constructor }
public Person(Person p) {
this.name = p.name;
... etc
}
}

In Java, class instances like instances of Person are reference types. This means that when you perform an assignment, you are merely copying a reference to an instance.
In your code, person and cancelPerson both refer to the same Person instance and any operations you do on them affect that same instance.
You could make a copy of a Person instance first if you don't want it to be modified.

Related

Unknown variable in class in Java

I think it's stupid but I must know what that thing is (in the red circle), is it a variable or something? This is tutorial from YouTube (https://www.youtube.com/watch?v=lF5m4o_CuNg).
I want to learn some about this but when I don't even know name of that I can't search info about this.
That are variables of specific types which are available in android. They store information about objects which are defined in some xml files. Usually their purpose is to add some logic to some graphic objects like text field or button.
TL;DR: Those are called attributes
Java is an object-oriented programming language. It means that we can create classes, with attributes (variables) and methods (functions), to represent (abstract may be a better word) concepts of the real world.
Let's say we want to represent a person in our program. We need to store the person's name and their e-mail address.
We can create a class Person with 2 attributes: name and email.
public class Person {
String name;
String email;
}
Now we can create an instance of a Person, and fill the attributes with values:
public class Person {
String name;
String email;
public static void main(String[] args) {
Person person1 = new Person();
person1.name = "Alice";
person1.email = "alice#gmail.com";
}
}
Let's say that we want to find out the e-mail provider of a Person. We can do that by creating a method.
public class Person {
String name;
String email;
public String getEmailProvider() {
String emailProvider = email.split("#")[1];
return emailProvider;
}
public static void main(String[] args) {
Person person1 = new Person();
person1.name = "Alice";
person1.email = "alice#gmail.com";
String person1EmailProvider = person1.getEmailProvider();
System.out.println(person1EmailProvider);
// This prints: gmail.com
}
}
The cool part about object-orienting is that you can create multiple instances of a Person, and fill their attributes with different values. So if you need to represent a, say, Bob, you can just Person person2 = new Person() and then set the attributes to the values that you want.
This is a very basic explanation of object-oriented programming. The internet has plenty of information about it, and I deeply recommend you to study this if you're a beginner.
Those are 3 variables.
"private" is the access modifier,
"EditText" is a variable type
"Password" is name of the variable

When I add to arrayList, it is adding the main notes list not the objects

I have a Person object that has been initialized and if I call the method like getName I can retrieve them.
public Person( String fName, String lName, List<Role> roleList) {
this.firstName = fName;
this.lastName = lName;
this.roleList = new ArrayList<Role>();
}
Each Person needs to have a list of roles so I have a list called roleList which I initialize using List<Role> roleList = new ArrayList();
when created it is passed as
testDriver = new Person("Mike", "Joy", testRoleList);
testDriver2 = new Person("Rich", "Johns", testRoleList);
In my calling class i want to add an item only to that staff members testRoleList. For this test i have made testRoleList public but I do have a getter which retrieves the testRoleList;
Role roleToAdd = Role.DRIVER;
// Only add the new role to the test driver
testDriver.testRoleList.add(roleToAdd);
But when you run this it does add the role, but if I try to retrieve the size of the testDriver and testDriver2 list using:
System.out.println(testDriver.testRoleList.size());
System.out.println(testDriver2.testRoleList.size());
The resulting list size is 1 for both list even though I haven't added a role to the testDriver2.
How can I just add the role to just testDriver or Just testDriver2
The thing is that whenever you create a new Person, the passed List will be overwritten with a freshly created new empty List.
So if you add something to the list, for example by:
testDriver.testRoleList.add(roleToAdd);
And after that create a new Person:
testDriver2 = new Person("Rich", "Johns", testRoleList);
Then the list will be empty again, because you have this code in the constructor:
this.roleList = new ArrayList<Role>();
You need exactly to know what your code does, change it so it does what you want. At this point it may be good to say that it is not a good design to change passed parameters by overriding them.
If you want something like a global List of roles, then it is not the task of the class Person to initialize this List. Let some other class do this job, pass the reference to the list to Person as you already do and then do not override it with a new reference. Save it, use it, add something, but not recreate it.
But if you want every Person to have its own List of roles, then there is no need to pass a reference from outside. In this scenario it is the task of the class Person and only of this class to manage such a List.
In this case you should remove the List parameter from the constructor but create a List as member variable, then offer some methods to interact with it. Here's an example:
public final class Person {
private final List<Role> mRoleList;
public Person(final String fName, final String lName) {
...
mRoleList = new LinkedList<>();
}
public void addRole(final Role role) {
mRoleList.add(role);
}
public boolean hasRole(final Role role) {
return mRoleList.contains(role);
}
public List<Role> getRoles() {
return Collections.unmodifiableList(mRoleList);
}
}
Then you can do such stuff:
Role r1 = ...
Role r2 = ...
Person person1 = new Person("a", "a");
Person person2 = new Person("b", "b");
person1.addRole(r1);
person1.addRole(r2);
person2.addRole(r2);
And the result is what you would expect, person1 has r1 and r2, person2 only has r2.
As side note, maybe a Set instead of a List reflects better what you want your roleList to be. Queries like contain then are very fast (O(1)), in a List they are very slow (O(n)).
In simple words, you are referring same object testRoleList, in both of your objects testDriver, testDriver2.
When constructing the Person object, pass List of Roles by constructing different List holding Role for each Person object.
Set is better than a List from performance point of view.
If Roles are limited and well decided, you could use EnumSet in place of ArrayList. Here also, you need to initialize different EnumSet "Role" objects for different Person objects.
To avoid Synchronization issues, use Collections.synchronizedSet.
Set<MyEnum> s = Collections.synchronizedSet(EnumSet.noneOf(MyEnum.class));
Refer https://docs.oracle.com/javase/8/docs/api/java/util/EnumSet.html

Passing parameter that does not exist to method [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am fairly new to Java proramming, as I have already stated in the title I want to pass some parameters that could or could not exist as instances of a class. If it does not exist, I want to create it. My code so far:
public class TestClass {
public static void main(String[] args) {
Person Ted = new Person();
Person Jack = new Person();
Item it = new Item(Ted);
Item itSec = new Item (Pierce); //Person Pierce doesn't exist => should be created
}
}
public class Person {
public Person(){
//some code
}
}
public class Item {
public Item(Person name){
if(!(name instanceof Person)){
Person name = new Person(); //create that missing instance
}
else{
//some code
}
void getItem(Person name){
System.out.println(name);
}
}
You misunderstand some things.
You can't use an identifier before it's been declared. The following is not correct in your code:
Item itSec = new Item (Pierce);
That's because you didn't declare Pierce before this line. You don't have to create an instance of the class, but you need a valid identifier. You should have declared it before this way:
Person Pierce;
At this moment the identifier, or the reference, is empty, so to say, or it is equal null. All object references which are not local are initiated this way, or they are equal false or 0, whichever is correct for their type. The result is the same as if you declared explicitly:
Person Pierce = null;
But let's move on. Say the reference has been declared. (Btw, Java uses camelCaseNotation for variables, so pierce would be correct.) Let's say we're at a point when Pierce is null or refers to some object, we don't know. Now we call this:
Item itSec = new Item (Pierce);
new Item(Pierce) calls the constructor public Item(Person name){...} in the class Item, which you should know. But now, in that constructor there's the line:
if(!(name instanceof Person)){
which you misuse. What this line is checking is not if the variable name equals null or an existing object, but variable type of name is a subtype of Person. Which will always return true in this place, as the function heading public Item(Person name){...} says this: the function is public, is a constructor, and the argument is of type Person (so Person or a subtype).
What you want to say here is this:
public Item(Person name){
if(name==null)){ //if the reference is empty
this.name = new Person(); //I'll explain this below
}
else{
this.name = name; //otherwise the local "name" will stay null
}
}
I used this.name and it was a jump ahead. Why? In your code that is Person name = ..., which is not correct as that name wouldn't last once the constructor's finished. You need a field in the Item class object, which will hold this value. So the Item class might be defined this way:
public class Item {
Person name;
//...
}
And now the field name holds the value assigned in the line:
this.name = new Person();
You need to use this to disambiguate which name you means. One is the Item class field, the other one is Person name the constructor parameter.
Now, we go back to the main function. If you want the variable Pierce to reference the newly created Person, this still needs to be done. The assignment can take place here, but first you'd have to create a function in the class Item that returns the value of its field name. So:
getName() {
return name;
}
And now call it from the main function:
Pierce = itSec.getName();
That's it. Finally, this function doesn't make sense:
void getItem(Person name){
System.out.println(name);
}
}
It doesn't get any Item. It only prints what you pass to it. And this doesn't mean that if you call it with getItem(Pierce), you will see "Pierce" on the screen. It will call the toString function in the object Pierce denotes, and as it is, you will get a standard object identifier. But if you define a function:
void printItem() {
System.out.println(name);
}
Then you can call it this way. For an existing object itSec:
itSec.printItem();
As for a getter function, it should return what you ask for, but that's another story.
What do you expect without instancing?
Person Pierce = new Person();
Item itSec = new Item (Pierce);
You cannot use a variable that does not exist...
Item itSec = new Item (Pierce);
The snippet above will never work because Pierce is undefined.
The code:
if(!(name instanceof Person)){
Person name = new Person(); //create that missing instance
}
Does not really make any sense, because that is the same as calling
Person Ted = new Person();
Person Jack = new Person();
Wherein the Person instance does not actually contain any data (unless you have some magic going on when instantiating the Person!)
I assume what you really want to pass is not an object whose variable is the name of a person, but rather a Person object that contains the name of the person.
If so, your code should be like this:
Person p1 = new Person("Ted");
Person p2 = new Person("Jack");
If you really want to do some instantiation if something does not exist, you might be able to do something like this:
Item(String personName) {
if(isExisting(personName)) {
getPerson(personName);
} else {
Person p = new Person(personName);
}
boolean isExisting(String personName) {
// Check if person exists somewhere
}
Person getPerson(String personName) {
// Retrieve the Person instance with the same person name.
}
if(!(name instanceof Person)){
Person name = new Person();
}
is meaning less because 'name' is always object is instance of person in this situation..
Item itSec = new Item (Pierce);
Pierce is not an object.. We can pass only Person object to constructor of Item class.. There is no any method to create an object of any class by just passing unkown variable..
Item itSec = new Item (Pierce); //Person Pierce doesn't exist => should be created
If it does not exist, I want to create it.
There's no "if" about it. The code never declared that variable, so it will never exist. (And never compile in its current state. Surely your Java compiler is telling you this.) Given that it always needs to be created, just create it:
Person Pierce = new Person();
Item itSec = new Item(Pierce);
Edit: Based on ongoing comments, it sounds like you want to have something more like a Map. Consider an example:
Map<String,Person> people = new HashMap<String,Person>();
people.put("Pierce", new Person());
The Map would basically be a collection of key/value pairs where the name is the key and the Person is the value. You can dynamically add/edit/remove elements to the collection as you see fit.
Then to use it, you'd call another operation on the map:
Item itSec = new Item(people.get("Pierce"));
You could use various operations to check if a value exists in the collection, add it, etc. You might even extend the class to add your own operations which create one if it doesn't exist when trying to get it.
Java won't dynamically create variables for you if a variable doesn't exist, but operations on a Map (or potentially other similar structures) can check if an element exists, add it, remove it, etc.

Get the object that an object is assigned to, how?

I dont know how to really ask this.
But like...
Student stud1 = new Student("Shady");
Student stud2 = new Student("Nick");
Student stud3 = new Student("Name");
stud2.addBook(new Book(Book.BOOK_MISERABLES, 3););
Now if we assume we have the following variable in the Book class:
private Student owner;
And now the question, inside the constructor of "Book" -> Is it possible to get the "stud2" object it's being called to? Without adding an additional parameter to the constructor? If so, how? I think it's possible... So it will be something like this:
private Student owner;
public Book(int bookNum, int weeks){
this.owner = this.GET_THE_TARGET_THIS_IS_CALLED_ON;
this.bookNumber = bookNum;
this.time = weeks;
}
What you're asking is not directly possible. You will need to either
Pass a reference to the Student instance to your Book constructor
or
Use a setter inside the Book class to set the value of the owner field to your Student instance.
The latter would be a method that looks like this:
public void setOwner(Student owner) {
this.owner = owner;
}
Additionally, you may want to modify your Student.addBook method to call this setter, like this:
book.setOwner(this);
As you mentioned in your comment, you can traverse the stack using Thread.currentThread().getStackTrace() However, you'll be unable to obtain an object reference using that technique. You can obtain the class or method name but the uses for that are limited unless you intend to construct a new instance. That's all highly unorthodox and not at all appropriate for this situation.

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.

Categories

Resources