Object list within an object - java

I have created an object that contains an Arraylist and that Arraylist contains objects. My question is, how do i point to the objects in the Arraylist?
the original Object contains:
some attributes,
list = new arraylist
The List contains:
14 objects of similar data

This seems like a fairly simple task, but because you did not give me your exact code, I am just going to assume.
Let's say this is the class of the object that you were talking about
public class ClassA {
public ArrayList<Integer> list = new ArrayList<>(); //I guess integers are "similar data"
}
Now you have that object, called obj
ClassA obj = new ClassA ();
You can just access the array list by doing this
obj.list
For example you can add an item to the array list like this:
obj.list.add(10);
And you can retrieve the first item
obj.list.get(0);
Easy!
If you think you understand little of the above, I'll explain. If you think you understand it completely, you can just accept the answer and go.
Almost every class declare members. And so does your class, ClassA. Any accessible member can be accessed using .. We call it the dot operator.
And what is an accessible member?
Different access modifiers provide different accessibility, read this to find out more: https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html In the above example, list is a member, and it is declared public This means that it is accessible everywhere.
This is why you can access it using ..
Actually, I think you must have used this technique before! When you call
System.out.println ("Hello World");
You use the dot to access members!
In the System class, there is a member called out. out is of type PrintStream. In PrintStream class, there is another member called println! See? that's how Java works.
If you still don't understand, read this part again. If you understand, please click that green tick to accept the answer.

Related

How is it possible to define a List, or similar data type. of the same class into a class?

I cannot understand how something like that is possible, right now I've an structure like the following in a code I've been passed:
public class DayhoursItem {
#SerializedName("code")
private String code;
#SerializedName("name")
private String name;
#SerializedName("dayhours")
private List<DayhoursItem> dayhours;
As far as I know in order to use dayhours, you would need to define a DayhoursItem that would need to define a list with a DayHoursItem object that would need to define a list with a DayHoursItem object... and so on.
The code is working but I cannot understand why, so I'd like to know how exactly that can be (how is the way it's behaving).
Simple: because any reference in java only "identifies" the corresponding object.
This means: when you define a class, and instantiate it, all your fields only point to these other objects. Each object has its own storage on the heap.
So that dayhours field simply points to a List object, that has its storage elsewhere in the heap. And it doesn't matter whether that list is empty, or contains other DayHourItem object: there is always only one "pointer" to that list object, from the owning DayHourItem.
There is no recursion here. In other languages, similar constructs might very well be illegal.
Of course, when say the constructor of the DayHourItem class tries to create another DayHourItem object (to be added to that list), then you have a recursion, and you run out of memory quickly.
So the point is: such "self references" can create problem, but that isn't necessarily always the case.

How does ArrayList.get return its objects?

Context: I'm making a mini-interpreter-ish calculator thing. I figured that the best way to hold the symbol table was to make an ArrayList of an Object that I've defined (name of the object is WiP). Setting up the ArrayList looks like.
ArrayList<miniVariable> vList = new ArrayList<miniVariable>();
Simple enough, and the miniVariable Object contains the following variables
public String name;
public double value;
public boolean initialized;
They are public because I already made setter/getters in the class with the ArrayList, when I didn't realize you could make one of Objects, and I don't want to move everything over. I probably should.
Question: If I were to call vList.get(index) .value = 5; would it actually change the value being stored in the vList(index)'s value variable? Or does .get(index)just return a copy of the data, and so changing this copy doesn't actually do anything?
It changes the value on the original instance, as one would expect.
Creating a copy of an object in Java only happens explicitly (and usually with some difficulty at that).
A few other notes:
Class names in should be CapitalCase.
Implementing getters and setters on an object holding a list of objects is bad practice as it violates encapsulation. If you're implementing getters and setters, it's best to put them on the class they apply to.
What you are storing in the ArrayList is not the object itself, but reference to object.
So when you do vList.get(i) it is returning you the reference that you previous put in. Which means you are going to access the same object that you previous put in the list, instead of a copy of it.
Get yourself familiar with one of the basic concept of Java, which is Reference and Primitive types.
Some off-topic suggestions:
Make sure you are aware of Java's naming convention. For example, for the class name, it should be MiniVariable instead of miniVariable.
Just to be more accurate: "and the miniVariable Object contains the following variable", MiniVariable is a class, but not an object. You may say "and a MiniVariable object (instance) contains these member fields", or "in MiniVariable class defined the following member fields"
All collections objects stores reference to object , if you change any thing on object directly(accessing through collection) or indirectly ( already have reference of it) it will change the state of the object stored in collection

What do you call this object in Java and why do you use?

So I'm working on with two class now and just learned to do this, yet still don't know why is this possible and what this is called. Class variable? Objects creating objects?
And in the setter method, why the default value is null? is it like String?
From what I'm assuming, 'RetailItem item' is like it combined the whole RetailItem class and creating a new variable in another class with its feature.
There are two classes named CashRegister and RetailItem.
Here goes the instance 'RetailItem item' from CashRegister with a setter.
public class CashRegister
{
private RetailItem item;
public void setItem (RetailItem newItem)
{
if (newItem != null)
{
item = newItem;
}else{
item = new RetailItem();
}
}
}
RetailItem() is a default constructor from RetailItem class.
What does item = new RetailItem(); mean?
I don't know where am I even going to start studying. What am I missing?
I have some trouble understanding your English, so I might have misinterpreted some of your questions.
What do you call this object in Java and why do you use?
I don't know which "object" you are referring to.
... yet still don't know why is this possible and what this is called.
It is just called this. There is no other term for it.
Class variable?
No. this is not a class variable.
Objects creating objects?
(Huh?) No. this is not "objects creating objects".
And in the setter method, why the default value is null?
Because that is the way that Java defined. Any instance variable (like item) whose type is a reference type has a default initial value of null.
(Why? Because that is the only value that makes sense from a language perspective. Anything else, and there would need to be some way for the programmer to say what the default is. Compilers can't read your mind!)
is it like String?
Not sure what you mean. But if you are asking if you would get the same default value behavior if item had been declared with type String, then Yes.
From what I'm assuming, RetailItem item is like it combined the whole RetailItem class and creating a new variable in another class with its feature.
Not exactly. What RetailItem item is actually doing is declaring a variable in which you may then put a reference to a RealItem object. This variable has the default value null .... until some other value is assigned to it.
What does item = new RetailItem(); mean?
That means create (construct) a new RetailItem instance (an object), and then assign its reference to the variable item.
I don't know where am I even going to start studying.
I recommend that you start with a good introductory Java textbook, or the Oracle Java Tutorial, or your course lecture notes. Ask your teachers.
But keep at it. If you work at it, you will get to the point where it all starts to make sense. Because, basic Java is a simple and consistent language. The language only gets complicated when you learn about generics, type inference / lambdas and .... multi-threading.

Java: The most efficient way to write pojo with ArrayList

What is the most correct and/or efficient way in terms of time & memory consumption to write simple pojo class containing ArrayList? (Regarding java mechanism for references, pass by ref', assignments etc.):
public class MyClass {
//1. Do we need to initialize here?
public List<String> mList = new ArrayList<>();
//2. Do we need to declare D. Constructor?
public MyClass() {}
//3. Need to initialize the list here or just pass?
public MyClass(List<String> list) {
this.mList = list;
}
//4. Better way for copy/assignment?
public void setMlist(List<String> list) {
this.mList = list;
}
public List<String> getMList() {
return this.mList;
}
}
Do we need to initialize here?
No, initialize it only when you need it. Make sure to check for null if there is possibility of using it without being initialized.
Do we need to declare D. Constructor?
If you do nothing in it, I don't really see the point of having it. Note that some people prefer to still declare it writing a comment in it and indicate that it should do nothing :
public MyClass(){
//NOP
}
See NOP. This won't change anything related to memory usage. However logically, the default constructor should initialize the list instead of initializing it at the beginning. So we have two options, we pass one that already exists (with the parameterized constructor) or we use the default constructor and create an empty list.
Need to initialize the list here or just pass?
Just pass, else what would be the point of receiving it as an argument ? If you initialize it and re-assign that would make no sense. You may want to check if the received one is null and initialize it otherwise.
Better way for copy/assignment?
If really you want to make a copy, you might want to check Collections#copy. However, this is not the point of setter, what you have done here is correct.
This is impossible to answer without knowing about your intentions. There's a surprisingly large number of design decisions you have to make, even when writing a "simple pojo class containing ArrayList". Here are 8 off the top of my head, but there are many, many more.
Do you want to make the field public or private? (probably private.)
If private, do you want to provide a get method?
Do you want to provide a set method, or do you want the field to be initialized once and for all in the constructor?
Should the argument to your constructor and/or set method only accept a List<String> or will you allow something more general, such as Collection<? extends CharSequence>?
Do you want people using your class to be able to modify mList? (This is different from reassigning mList.)
Do you want to write subclasses, or do you want the class to be final?
If you want to write subclasses, do you want to make any of the methods final?
Do you want to provide a constructor with no argument that initialises the ArrayList to a sensible default value?
The most subtle one of these questions is the 5th. Suppose somebody does this
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
myClass.setMList(list);
and then later does this
System.out.println(myClass.getMList());
They may expect to see [a, b, c], but this may not happen because it is possible to modify the internals of myClass in between. For example:
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
myClass.setMList(list);
list.remove(1); // Modifies the List stored by myClass
System.out.println(myClass.getMList()); // prints [a, c]
If you don't want this kind of thing to be possible you'll have to write a class that copies List objects in the constructor, setter and getter. This will have consequences for performance (but will be tiny for small lists).
There are no right or wrong answers. You need to think through who is using the class, why they need it, and weigh up all the relevant factors when answering all of the above questions.

How do I call to a void method to incorporate it in a method in a different class?

My assignment is to create a program that simulates a simple online shopping program.
we have to:
create a main menu with 3 options and then a submenu when selecting the 2nd option on the main menu.
I'm unsure how call a method from another class for example:
I have been given a method:
public void start() {
which is in the file "GroceryStore.java"
I am supposed to create a topMenu method which when the user inputs "1" calls to the method:
public void displayItems(){
^in file called "Stock.java"
which then prints out an array of items that online store has in stock. The array in the
Stock.java is
private SalesItem[] items;
Can anyone tell me how to do this? I have to do this for several things and I'm hoping I can apply the skeleton of this to the rest of the cases.
For now, I'm going to assume that Stock is an instance type(it sounds like an instance type), and It would make sense that your GroceryStore would have a reference to 1 or more Stock items.
Your Stocks will have to be instantiated with the new keyword. so
Stock myStock = new Stock(/*parameters for constructor*/);
after you do that, you can call the displayItems method of myStock like so
myStock.displayItems();
so start() is in the GroceryStore class.
So in a public static void main class you would go :
GroceryStore gs = new GroceryStore();
gs.start();
In your GroceryStore class you would have a new method which looks like (You may want to have the Stock stock = new Stock() line in the constructor of the GroceryStore object-- would make more sense:
Stock stock = new Stock();
public void topMenu(int parm){
if(parm==1)then{
stock.displayItems();
}
}
And then finally in the Stock class you have the displayItems method which may look like :
public void displayItems(){
for(int i=0;i<items.length;i++){
SalesItem temp = items[i];
System.out.prinlnt(temp.toString());//or this may be temp.getName() or whatever returns a string from this SalesItem object - I dont know what it looks like - you never said!
}
}
It is however essential you actually understand what is going on here not just copy paste and run?! This wont actually do anything anyway until you have a call to the topMenu method passing it 1, so you will need to workout how you are going to interact with your gs object whether its by keyboard input, mouse click on a gui or something else :)
To call a method outside the current instance you have multiple options:
make the method static (so that it won't be attached to any particular instance) and call it through MyClass.method(), this has sense if it is a stateless object, mostly an utility method
create a static instance variable that can be accessed (so method is not static but the specific object is), then call it through SomeClass.stock.method(), this has sense when you want a single object of a specific type throughout the program
create a normal instance variable inside the class from which you want to call the method (this has sense just if the object contained is used in a HAS-A relationship). Then you call it simply doing this.stock.method() (you can omit this)
You need to tell the compiler where to get the methods from if the method is not in the same class. The best way of doing this would be to create an object that refers to the class you're trying to reach (using the New Java keyword and the appropriate syntax, i.e. ClassName objectName = new ClassName() - you may want to include any parameters you may have).
Have a look at this other StackOverflow answer - the user had a question very similar to yours, so it may help.
Also, there is a pretty good tutorial on objects and classes on TutorialsPoint. I suggest you have a look at it and give it a go. Try understanding the concept behind what you're trying to achieve first - I can guarantee you it will help later on as this is a very fundamental concept in OO programming.

Categories