I want to have one list for accessing from any class. But when I try to reach a list from another class it throws NullPointerException. I tried to solve it with constructors, but in this case every class which have an object of the main class (where the list stores) create a new list by calling constuctor. But I need unique list which can be accessed, modified and etc. from other classes. How could I manage this?
Asked
Active
Viewed 460 times
-3
-
3You'd probably start to manage this by providing some more information, e.g. a [mcve]. Currently I have no idea what you're actually after or which problems you try to solve - some sort of code is very likely to clarify it. – Thomas Apr 18 '17 at 12:24
-
6so you´re looking for a `static` `List`? – SomeJavaGuy Apr 18 '17 at 12:24
-
Look for keywords like: static, singleton Make a try and when you then still have problem, post some code and we can help you – Rene M. Apr 18 '17 at 12:28
-
Just be careful when designing around singletons. They are [often considered an antipattern](http://stackoverflow.com/a/1448407/6902543) when testing your code. – Michael Peyper Apr 18 '17 at 12:36
-
So what's the difference between singleton pattern and static? – Hasan Shans Apr 18 '17 at 15:52
2 Answers
-1
Use the concept of Singleton class.
class List
{
private static ArrayList<int> intlist;
private static List list;
//private constructor [singleton class]
private List(){
intlist==new ArrayList<int>();
};
private static List getList()
{
if(this.list==null)
list=new List();
return list;
}
public getIntList(){return this.intlist;}
}
class A
{
public void Test()
{
List l=List.getList();
l.getIntList().add(1);
}
}
class B
{
public void Test()
{
List l=List.getList();
l.getIntList().add(2);
}
}
Now class A and class B are getting same list to put value into it.

KOUSIK MANDAL
- 2,002
- 1
- 21
- 46