Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Now, I have encountered this problem:
I have a non-empty array list declared as original. Then I do this :
ArrayList<ArrayList<Integer>> temp = (ArrayList<ArrayList<Integer>>) original.clone();
temp.get(0).set(1,-1) ;
but the result was that unexpectedly the element at index 1 in both lists were changed.
How can I fix this problem ?
clone makes a shallow copy of the ArrayList. Either make it's Deep Copy since the ArrayList is object type so it can also make new object of it's reference.
You have to deep copy, you can try below code
for(int element:original)
{
temp.add(element);
}
clone makes a shallow copy of the ArrayList. In a sense, this means affecting the ArrayList from one reference also affects the other reference.
Instead, use new ArrayList(original).
Edit: My mistake. You'd have to go through the contents of your ArrayList and clone each object inside. Unfortunately for you, you have ArrayLists inside your ArrayList, so you'd have to do a lot of iterating if you want distinct Integers.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I came across this code. I was wondering if this is possible. As you can see, aList is an ArrayList which .adds() itself.
ArrayList<Object> aList;
aList = new ArrayList<Object>();
aList.add("cat");
aList.add(aList);
aList.add(12);
int size = 0;
Iterator<Object> it = aList.iterator();
while(it.hasNext()) {
it.next();
size++;
}
System.out.print(size);
Yes, it is possible. There are no restrictions on the elements you can add to a ArrayList<Object>.
And you can iterate the list, and do various other things with it.
But don't call toString() on it because you might get a StackOverflowError.
UPDATE - For (at least) Oracle / OpenJDK Java 6 and onwards, the toString() method inherited from AbstractCollection will detect this "self reference" cycle and show it as (this collection) rather than going into an infinite recursive loop.
However:
This is an implementation detail. It is not part of the specification.
I don't know if this applies for all Java versions; i.e. prior to Java 6, and Android versions.
This doesn't apply for 3rd-party List classes that don't extend AbstractCollection. (For them, you would need to check the implementation code to understand what would happen.)
It doesn't apply if the self-reference cycle has more than one "hop"; e.g. list A contains list B, and list B contains list A. In such cases you would get infinite recursion and a StackOverflowError.
So caution is advised.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Let's say I have
ArrayList<Citizen> citizen1 = new ArrayList<Citizen>();
ArrayList<Citizen> citizen2 = new ArrayList<Citizen>();
ArrayList<Citizen> citizen3 = new ArrayList<Citizen>();
is it possible to have an arraylist which compromise them all?
List<List<Citizen>> mainList= new ArrayList<>();
You can go with List of List.
Also need to consider below points.
I recommend using "List" instead of "ArrayList" on the left side when creating list objects. It's better to pass around the interface "List" because then if later you need to change to using something like Vector (e.g. you now need synchronized lists), you only need to change the line with the "new" statement. No matter what implementation of list you use, e.g. Vector or ArrayList, you still always just pass around List.
In the ArrayList constructor, you can leave the list empty and it will default to a certain size and then grow dynamically as needed. But if you know how big your list might be, you can sometimes save some performance. For instance, if you knew there were always going to be 500 lines in your file, then you could do:
You can have a List of Lists of Citizen, like this: List<List<Citizen>>= new ArrayList<>();
You can use the addAll() methods of List and Collection to add to one List all the elements of another list.
If using at least Java 8, you can do various things using the Streams API: Stream.of(), Stream.concat(), and maybe others.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I want to know whats the difference between creating an object[] objects and List<object> objects?
For example lets say I have a class for a book and i wanted to create an object array of books what would the best approach be?
Simply they are two differenct structures.
Object[] obj = new Object[4]; // Creates an array of 4 Object
List<Object> obj = new ArrayList<Object>(); // Creates a list
// (ArrayList in this case) of Object
An array is a structure that can't change its size.
A list can change it.
A list has many different implementations:
ArrayList
LinkedList
Vector
other implementations also custom implementations
An array is a predefined data structure that can't be changed.
A list has many predefined functions not present in an array.
With a list, you do not have to give a specific number of Items, and you can add whenever you want.
If you know exactly how many book instances you need, you can go for an array. But I prefer to use Lists, since it's more comfortable (imo)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm trying to implement a stack with an Array List.
BlueJ tells me that "size" has private access in java.util.ArrayList even though the Array List is public, when I'm compiling.
int stackLength = stackStorage.size;
System.out.println(+stackLength);
And if I change the line to..
int stackLength = stackStorage.size();
the program compiles and I get a nullPointerExcetion when I run the function.
I don't understand why this is happening because a value cannot be manually assigned because the value needs to come from the stack size.
Any help appreciated, cheers.
You can't directly call for the variable (because it's a private field). You should use stackStorage.size() instead. Also make sure stackStorage is actually instantiated.
You most probably have:
ArrayList<Object> stackStorage;
However you must instantiate it somewhere like so:
stackStorage = new ArrayList<Object>();
This may also be done on the same line:
ArrayList<Object> stackStorage = new ArrayList<Object>();
Once you have created this ArrayList do note that it still doesn't have any elements in it. In order to actually add an Integer to the array simply do:
stackStorage.add(number);
And after you do that, if you call stackStorage.size() it should return 1, meaning there's one element in the ArrayList. If you wish to add more, simply use the add() method. Also make sure you add the same object as you instantiated it with. You can't store String in ArrayList<Integer> for example.
Full-code example:
ArrayList<Integer> stackStorage = new ArrayList<Integer>();
stackStorage.add(10); //Now has value `10` in `index[0]`
System.out.println("index[0]: " + stackStorage.get(0)); //Prints 10
System.out.println("stackStorage.size() = " + stackStorage.size()) //Prints 1
In your case replace Object with Integer if you wish to store integers. NullPointerException means your object is still null when you tried to call size(). This should solve your issue. If you're not sure what null is or don't quite understand what NPE(NullPointException) is I suggest reading about it and if you have further difficulties, posting it here.
That's because size is a private field and hence you don't have access to it, where size() is a public method that you can use. Therefore call size() to get the size of the ArrayList. The NullPointerException has nothing to do with size it is simple because your object is not initialized, make sure you initialize your objects before using them.
List<Something> list = new ArrayList<Something>();
size is a private variable
size() is a public method
For getting the size of the arrayList , you need to use size() and before calling size() dont forgot to intialize the array List like below .
List list = new ArrayList();
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
If I declare a new list like this:
List<String> listExample = someFunction();
what list interface implementation will be used?
EDIT: Thanks for the answers so far. What is considered as the clean way to do this, should I always declare list with new?
As Eran commented that totally depends on what someFunction(); returns .Both ArrayList<E> and LinkedList implements List interface .
You can try ,
System.out.println("" + listExample.getClass());
to find out the which has been implemented. From docs,
public final Class<?> getClass()
Returns the runtime class of this Object. The returned Class object is
the object that is locked by static synchronized methods of the
represented class.
Whatever you are building e.g. LinkedList, ArrayList, Vector, Stack in and returning from someFunction() will be implemented with listexample. If you are using List interface reference, it has one benefit, that you can assign any type of object to it (LinkedList, ArrayList, Vector, Stack).
eg if u give
List listExample = new ArrayList();
Then the Object will be created for ArrayList and list is just an instance of listExample.
and you can use getClass() for that listExample to view