Reputation: 8062
I have an implemented data structure called List
(it's a singly linked list). I have the following code in my Java program:
List[] Adjacent = new List[N]; // Trying to create an array of N List objects
Suppose N = 6. I want Adjacent
to be an array of six elements where each one of them is a List
object itself. But when I try to access it, the array is actually an array of N null references. What is going on?
Of course I did the following to solve my problem:
for (int p = 0; p < N; p++)
Adjacent[p] = new List();
But that's not what I really want. Is there a more efficient/nice way to do it?
Upvotes: 1
Views: 2857
Reputation: 533502
When you have
List list;
this is a reference, not an object. To have an object you have to create one with new List(...)
. There is no way to work around this. You have to initialise your references to actual objects.
Also, it is far worse to be creating a class which does the same thing with a similar name to something already built in. I suggest you use a List of List like this:
List<List<String>> listofLists = new ArrayList<>();
for(int i = 0; i < N; i++) listOfLists.add(new ArrayList<>());
It is more efficient for you to reuse existing classes.
Upvotes: 3
Reputation: 298153
There will be a “nice” way to to it with Java 8:
MyObject[] array=Stream.generate(MyObject::new).limit(N).toArray(MyObject[]::new);
Stream.generate(MyObject::new)
will create an unlimited stream of objects provided by a Supplier
which is the default constructor of MyObject
in our case, limit(N)
obviously limits the number of objects and toArray(MyObject[]::new)
will store the objects into an array constructed by an IntFunction<A[]>
that constructs an array using a specified int
which is set to the equivalent of new MyObject[i]
in our case. The stream will provide the limit N
for that i
parameter.
Though the last part is not the real spirit of streams. Normally, you would direct the stream to the consumer dealing with the objects and omit the array completely.
Upvotes: 3
Reputation: 1976
Suppose N is always 6 ...
List[] l = new List[]{new List(),new List(),
new List(),new List(),new List(),new List()};
Upvotes: 0
Reputation: 2874
Nope. After create new array you should fill it manualy. Of course we have Arrays.fill(array, object)
method but it will set the same object to all positions in array.
Upvotes: 3