Unable to see ArrayList elements in another object in Java - java

I'm trying to view the elements of an ArrayList in a different class but it shows that there is nothing. In the other class, you can see the element in the ArrayList though.
Here are the codes.
First class
import java.util.ArrayList;
public class Test {
ArrayList<String> inventory = new ArrayList<String>();
public void test() {
inventory.add("item");
}
public void check() {
System.out.println(inventory);
}
}
Second class
import java.util.ArrayList;
public class Test2 {
Test testObj = new Test();
public void test2() {
System.out.println(testObj.inventory);
}
}
Main class
public class Main {
public static void main(String[] args) {
Test testObj = new Test();
Test2 test2Obj = new Test2();
testObj.test();
testObj.check();
test2Obj.test2();
}
}
Output
[item]
[]

In java Class level variables are Object associated until unless they are not declared static.
By means of Object associated is that when a object is initialized with new keyword in Java all Object will be having it's own memory and own class variables.
In your case inside main method when you create a Object of Test class and when you create a another test class object inside Test2 class, both will be totally independent of each other. And both will be having their own memory and own variables.
If you want that to get the updates of inventory variables from first object to be available in another object you need to declare it as static and should be initialized inside static block. Static variables are shared across all objects of class. As below:
static ArrayList<String> inventory;
static {
inventory = new ArrayList<String>();
}

In your main method, you call the method that handles adding operation yet you do not call any add methods in the second class and in your main method.
testObj.test();
testObj.check();
This one shows that you add an item into the arraylist and show it. But in the second class you do not add anything but calling it. Therefore there is no way to show any element from that method. What has should be done is that you just need to call the adding method inside of the second class and then try to use the display method.

You didn't call test() method in Test2 class.
To make it work change the Test2 class as follows.
import java.util.ArrayList;
public class Test2 {
Test testObj = new Test();
public void test2() {
testObj.test();
System.out.println(testObj.inventory);
}
}

Related

How do i make a static reference to a non-static method?

import java.util.Iterator;
import java.util.ArrayList;
import java.util.Arrays;
class Main {
public static void main(String[] args) {
ArrayList<String> original = new ArrayList<>(Arrays.asList("afd", "asdf", "aavdd", "sajf", "adnf", "afd", "fjfn"));
String find = "afd";
String replaceWith = "asd";
System.out.println(replaceIt(original, find, replaceWith));
}
public ArrayList<String> replaceIt(ArrayList<String> original, String find, String replaceWith){
ArrayList<String> newList = new ArrayList<String>();
for(int y = 0; y<original.size(); i++){
if(!original.get(y).equals(find))
newList.set(y, original.get(y));
newList.set(y, replaceWith);
}
original = newList;
return original;
}
}
How do i call the replaceIt method? I'm confused and I need to make it so it prints the output of that function. I'm so confused somebody please help.
public ArrayList<String> replaceIt() is an instance method, it is only called from Main instances/objects.
public static void main is a static method of class Main, static methods can’t access instance methods and instance variables directly.
Therefor, to call replaceIt() method from static main method, make replaceIt() static.
public static ArrayList<String> replaceIt(/*arguments*/){
//your code goes here
}
Having non-static method in Main is a little odd. It's not like you are going to construct new instances of Main (say, the same way you would construct new instances of a Person class).
These type of generic helpers/utils functions usually go into some sort Utils.java or Helpers.java class, and are declared as static in these files. This way you would be able to invoke: Utils.replaceIt(original, find, replaceWith));
Because replaceIt() is an instance method, you simply need to create an instance of the Main class to call it -
public static void main(String[] args) {
...
Main m = new Main();
System.out.println(m.replaceIt(original, find, replaceWith));
}

Calling a method on an Object from within a Class vs from within a method

This might be a really elementary question but it puzzles me at this stage of my Java learning.
I have got the following piece of code:
package com.soti84;
import java.util.ArrayList;
public class InvokeMethod {
public static void main(String[] args) {
ArrayList<String> exams= new ArrayList<String>();
exams.add("Java");
exams.add("C#");
}
}
If I move the line that instantiates the ArrayList object and the calls on that object outside the method, the line that creates the object is fine but the add() method calls on the object are not allowed. Why is that?
package com.soti84;
import java.util.ArrayList;
public class InvokeMethod {
ArrayList<String> exams= new ArrayList<String>();
exams.add("Java");
exams.add("C#");
public static void main(String[] args) {
}
}
Thanks.
You simply can't do that code outside of methods. If you wanted to do this you would need initializer block or static block.
public class InvokeMethod {
ArrayList<String> exams= new ArrayList<String>();
{
exams.add("Java");
exams.add("C#");
}
Now that block is gonna execute when you create an instance. If your variable was static, you could make that block static (just add static before that block). Static block is gonna execute when your class is initialized. Those blocks can be quite convenient when you need a populated static list/map. Ofcourse, everything that is convenient in programming is probably a bad practice, and same here, those blocks are frowned upon by some people, they can be quite dangerous and lead to hard-to-find bugs (mostly about the order of execution).
In the two examples you are trying to achieve two totally different things.
In the first example you declare the ArrayList inside the main method, therefore the scope of the list will be just this method. The enclosing class has absolutely no connection with that ArrayList.
In the second one you try to create a data member called exams in the class InvokeMethod. That means, every instance of this class will have its own list.
The addition of the elements does not work, because "out of the methods" only declaration and initialization can happen. To fix that, you can use an initialization block:
public class InvokeMethod {
ArrayList<String> exams = new ArrayList<String>();
{
exams.add("Java");
exams.add("C#");
}
public static void main(String[] args) {
}
}
or, the constructor of the class:
public class InvokeMethod {
ArrayList<String> exams = new ArrayList<String>();
public InvokeMethod() {
exams.add("Java");
exams.add("C#");
}
public static void main(String[] args) {
}
}
Note: You can also retrieve this list from main method via an instance of the InvokeMethod class:
public class InvokeMethod {
ArrayList<String> exams = new ArrayList<String>();
public InvokeMethod() {
exams.add("Java");
exams.add("C#");
}
public static void main(String[] args) {
InvokeMethod invokeMethod = new InvokeMethod();
System.out.println(invokeMethod.exams.toString());
invokeMethod.exams.add("Delphi");
System.out.println(invokeMethod.exams.toString());
}
}
will print
[Java, C#]
[Java, C#, Delphi]
That's because "you're calling it from outside the function/method"
ArrayList<String> exams= new ArrayList<String>();
The line above means you're declaring it as the property of an Object. which means you can only access it inside a Method.
If you're going to place the following in your Main
exams.add("Java");
exams.add("C#");
This should work just fine, although you declared the "exams" outside the method.
As per Java language specification, class body declaration has Instance Initializer but don't has method invocation. So in your example ArrayList<String> exams= new ArrayList<String>(); is allowed inside class body but not exams.add("Java");
JLS excerpt :
ClassBody:
{ ClassBodyDeclarationsopt }
ClassBodyDeclarations:
ClassBodyDeclaration
ClassBodyDeclarations ClassBodyDeclaration
ClassBodyDeclaration:
ClassMemberDeclaration
InstanceInitializer
StaticInitializer
ConstructorDeclaration
ClassMemberDeclaration:
FieldDeclaration
MethodDeclaration
ClassDeclaration
InterfaceDeclaration
;

How is it possible to create object in Class definition itself?

I have some doubt on how this works, consider a simple Java program:
package com.example;
public class Test {
public static void main(String[] args) {
Test t = new Test(); (1) <---- How is this possible
t.print();
}
public void print() {
System.out.println("This is demo");
}
}
This is pretty straightforward program.
However, I have doubt at (1). We are creating an instance of Test, but this is still in the definition of Class Test. How is this possible?
Any explanation to help this would be great.
The instance will be created at run-time.
By then, compile-time is over and all of the code of your application (including all class definition) will be "ready".
Even if you call a constructor of a class that has not been encountered by the JVM up to that point, it will dynamically load the class (in its entirety) before executing the constructor call. Note that a) this might actually fail at run-time, in which case you get a ClassNotFoundError, and b) that cannot happen in your case, because you are calling the constructor of the class from itself (so it must have been loaded already).
The compiler does not run any of your code (not even things like static initializers) during compilation.
But it does make sure (during compilation) that every method or constructor that you are trying to call does in fact exist. Again, this could theoretically fail at runtime (if you mess up class files), in which case you would get a NoSuchMethodError.
First We have to Compile this Porgram using javac After Compilation It will give a Class File.
Now time to Execute Your Class Using java which Invokes JVM and load the Class File to the Class Loader.
java fileName.Class
And here
public static void main(String[] args) {
Test t = new Test(); (1) <---- How is this possible
t.print();
}
All we know static Content (either it is Variable or Method In Java) Of class loaded when ClassLoader loads a Class
As You see Main Method is a static Method. and So, It will Automatically Load into the ClassLoader with class File.
Now JVM First find the public static void main(String... args) in class. Which is a static Content means Its a part of Class but not a part of Class Instance. There is no need of Class Instance to Invoke this MainMethod`.
main(String... args) will be Invoked without getting Instance of the Class. In that Main Method , Your Class is Getting Instantiated
Test t = new Test(); \\here t is reference Variable to Test Class Object.
Now Because Class is loaded into the class Loader new Test(); will create a New Object in Heap memory Area of JVM and your method
public void print() {
System.out.println("This is demo");
}
will be invoked using t.print() Which is a Instance Method (Not Static), So It needs Class Instance to Invoke print() Method.
Q: Test t = new Test(); (1) <---- How is this possible
A: Because of the "static" in public static void main(String[] args)
The "static" means that method "main()" is independent of any specific class object.
You can create any class object you want - including a new "Test" object.
One of the benefits of defining "main" to be static is that you can use "main()" as a test method for the class. Each class can have it's own "main", and you can test each class individually by specifying that class in your Java command line.
For example:
public class MyClass {
public int add2(int n) {
return n + 2;
}
public static void main (String[] args) {
MyClass unitTest = new MyClass ();
System.out.println ("add2(2)=" + unitTest.add2(2));
System.out.println("Expected result=4");
}
}
Then test as follows:
javac MyClass.java
java MyClass
add2(2)=4
Expected result=4
This question has actually been asked and answered many times. For example:
Why is the Java main method static?
==================================================================
Here are a few more examples that illustrate the point:
public class CreateMyself {
private int value = 0;
private static CreateMyself m_singleton = null;
// EXAMPLE 1: You can legally create an instance in the constructor ...
public CreateMyself () {
value++;
// CreateMyself o = new CreateMyself (); // BAD!!! This will cause infinite recursion and crash your stack!!!
System.out.println ("Leaving constructor, value=" + value + "...");
}
// EXAMPLE 2: You can legally create another instance in a normal class member
public void createAnother() {
// But ... WHY??? Is there anything you can't do directly, in your own instance?
CreateMyself newInstance = new CreateMyself ();
System.out.println ("Leaving createAnother, value=" + value + "...");
}
// EXAMPLE 3: This is a common idiom for creating a "singleton"
// NOTE: for this to work, you'd also make the constructor PRIVATE (or protected), so the client *must* call "getInstance()", instead of "new".
public static CreateMyself getInstance () {
if (m_singleton == null) {
m_singleton = new CreateMyself ();
}
System.out.println ("returning singleton instance...");
return m_singleton;
}
// EXAMPLE 4: Creating an instance in "static main()" is a common idiom
public static void main (String[] args) {
CreateMyself newInstance = new CreateMyself ();
newInstance.createAnother ();
}
}
There are many other possible uses. For example, maybe you'll have a static method that does a database lookup and returns a list matching objects.
Note that most of the cases where it's really useful for a class to have a method where it creates an instance of itself are probably static methods.

Always need to make static

I am working on a project, and I have come across something i do not fully understand yet.
Every time I like to call a method from another class, or use a variable from a jform my netbeans says that I need to make it "static". Now I understand what static means, and I have created objects from the class that I use methods from, but even then netbeans says that I need to make the object static before i can use it in the MAIN() method. Even the jform variables like comboboxes.
can somebody please explain this?
thanks in advance!
EDIT:
this is some code from my project. It's very small but it should clarify the problem:
the Mainclass:
public class SpeeloTheek {
/**
* #param args the command line arguments
*/
public static Controller MainController = new Controller();
public static SummaryScreen MainSummaryScreen = new SummaryScreen();
public static void main(String[] args) {
// TODO code application logic here
MainSummaryScreen.setVisible(true);
MainController.SetFullScreen(MainSummaryScreen);
MainController.ComboBoxItemSelected(SummaryScreen.choiceBox);
}
the controller class:
package speelotheek;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class Controller {
//Method to make JFrame fullscreen//
public void SetFullScreen(JFrame frameToUse) {
frameToUse.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
public void ComboBoxItemSelected(final JComboBox comboBoxToUse) {
comboBoxToUse.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
WhichSummary(comboBoxToUse);
}
}
});
}
public void WhichSummary(JComboBox comboBoxToUse) {
System.out.println(comboBoxToUse.getSelectedItem());
}
}
EDIT2:
Thanks all :) I found the problem. I instantiated the class in the main method instead above the main method and it worked :)
In order to call non-static members of a class you need to instantiate an object.
Example:
Foo myObject = new Foo(); // myObject is an object of class Foo
Foo.callToStaticMember(); // static members can be called using the class name
myObject.callToNonStaticMember(); // non-static members require an object of the class
This is because your main method is a static method.
From a static method you can't call the non static method's or variablen.
You need to change your main method to a constructor.
Then this code will be executed when you make an new instance of this class.
If you're using Netbeans GUI Builder, what you want to do is work from the constructor, instead of the main method
public NewJFrame() {
initComponent();
jComboBox1.addItem("Hello");
// do everything with your components here
}
All the objects declared by the GUI Builder are non-static. They're not meant to be accessed from the main.
if you are trying to access non-static methods from the main method. It would not work. The reason being, that static methods/variables do not belong to the instance of the class.
If you do need to access a non static method in your main method of another class. the only way to do it is through the instance of the class.
So, you would need to say
MyClass object = new MyClass();
object.aMethod();
EDIT
Do you want your application to be all static? Basically, static would mean that it will have only one memory location. So, for eg: if a user selects a radio button on one screen. it modifies the value in your code, and another user selects another radio button, it will overwrite the previous user's value.
What you do need to do is something like this.
public static void main(String[] args) {
// TODO code application logic here
Application appObject = new Application();
appObject.setController(new Controller());
appObject.setSummaryScreen(new SummaryScreen()); // Or pass these values through a constructor. Setters are just one way to do it. Or better yet, use Spring DI.
appObject.performAction();
}
public Class Application {
public Controller MainController ;
public SummaryScreen MainSummaryScreen ;
.... getters and setters of these instance variables.
public performAction(){
MainSummaryScreen.setVisible(true);
MainController.SetFullScreen(MainSummaryScreen);
MainController.ComboBoxItemSelected(SummaryScreen.choiceBox);
}
}
While you are working within the main method, which is static
public static void main(String[] args){
}
you can only call static elements, such classes, enum or static methods.
If you want to call a method member of a class from your main method, you have two options
Make the method static
class ClassA{
public static void methodOne(){
}
}
public static void main(String[] args){
ClassA.methodOne();
}
Instantiate the class in your main and call the non-static method.
class ClassA{
public void methodOne(){
}
}
public static void main(String[] args){
ClassA classA = new ClassA();
classA.methodOne();
}
Advice
You have to take care while using static methods, because they share its memory.
when you create a new class ClassA classA = new ClassA();, for each new class you create, it stores its own non-shared memory variables, but when you use static methods, they share the memory which could be dangerous.

How to run a package from another package inside the same project?

I have two packages inside my project, a and b.
a is my "main class" that runs when the program runs but I need to make b run from a (if that makes sense).
I'm sure its something along the lines of PackageB.BMain but I'm not sure.
Edit:
Okay so I've learned a few new things, to start my main project is RevIRC, inside that I have two packages, MainChat and RevIRC, now when I run the program RevIRC is ran, I need to make Mainchat run when RevIRC is ran.
Like I said before I'm sure its something along the lines of RevIRC.MainChat.ChatMain() but I can't seem to figure it out.
You have 2 options:
Either create a new instance of B from A, like so: PackageB.BMain b = new PackageB.BMain();
Access the methods in BMain in a static way like so: PackageB.BMain.someMethod();`
Note that you can use either of these exclusively or mix them up together, however, it all depends on how you have written your BMain class.
So for instance:
package PackageB
public class BMain
{
public BMain()
{ }
public void foo()
{
System.out.println("This is not a static method. It requires a new instance of BMain to be created for it to be called");
}
public static void bar()
{
System.out.println("This is a static method. It can be accessed directly without the need of creating an instance of BMain");
}
}
Then in your main class (the class which has the main method):
package PackageA
public class AMain
{
public static void main(String[] args)
{
PackageB.BMain.bar();
PackageB.BMain bInstance = new PackageB.BMain();
bInstance.foo();
}
}
If you have two main methods it will either run from A or B. The JVM will choose the first main method it sees IIRC.
Have a standalone class that will have main. And create your classes there.. ?
import a.Class1;
import b.Class2;
public class MainController
{
public static void main(String args[])
{
Class1 class1 = new Class1() ;
Class2 class2 = new Class2() ;
//Both class no start at the "same" time.
}
}
if i am not wrong you want to run main method of class B from class A.
That you can call using B.main(arg[]);
eg :
package a;
public class A
{
public static void main(String[] args)
{
System.out.println("This is main method of class A");
B.main(null);
/*pass any args if you want or simply set null arg*/
}
}
package b;
public class B
{
public static void main(String[] args)
{
System.out.println("This is main method of class B");
}
}
i hope this simple example will clear your doubt.
you can refer to link which contains Java tutorial for beginners.

Categories

Resources