I've a problem that concerns the communication between Packages. This is the question, is it possible to have a list in a package and import this list into another package, so that i can use it there too?
This is the code:
// this is the first package where i create the list and i've create a method to return the list
package Pack1;
import java.util.*;
public class Lexer
{
public static LinkedList<Object> lst = new LinkedList<Object>();
public static LinkedList<Object> getList(){
return lst;
}
}
// After this, i add objects to "lst", so the list it's full of objects.
///////////////////////////////////////////////////////////////////////////////
//This is the second Package.
package Pack2;
import Pack1.*;
import java.util.*;
public class Parse {
//In the main i tried to create a List to contain the old one ("lst") but when i use the
//method getList nothing happens! So toString prints nothing.
public static void main(String[] args )
{
LinkedList<Object> list = new LinkedList<Object>();
list = Lexer.getList();
list.toString();
}
}
import
just allows you to refer to a class, or field without needing to use the full package name. It doesn't give to access to something you didn't have access to already. It just makes your code shorter.
If you want to pass a list
from one class to another (whether in another package or not) the simplest approach is to call a method and pass a reference with that list
.
What you are doing is using a global field. While that can work it is generally not a good idea as it makes scaling and testing your application harder.
Instead I suggest you avoid mutable static fields, and use a instance field instead. I also suggest avoiding returning a collection. If you need to to string a list add a method like
public String listToString() {
return list.toString();
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments