This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 8 years ago.
I have created simple shuffle method everyting seems okay but there is a problem which i can't find.
Here is my Code Below:
public static <E> void shuffle(List<? extends E> list) {
List<E> temp = new ArrayList<>();
while (list.size() != 0) {
E val = list.remove((int) (Math.random() * list.size()));
temp.add(val);
System.out.println(val);
}
System.out.println(temp);
list = temp;
}
This is the test case:
ArrayList<Integer> arr = new ArrayList<>();
arr.add(1);
arr.add(2);
arr.add(3);
arr.add(4);
arr.add(5);
arr.add(6);
System.out.println(arr);
shuffle(arr);
System.out.println("-->" + arr);
The problem is last print out method shows that arr is empty --> [] It Should be something like that [4,3,1,2,6,5]
Problem could be this line but i did not understand why ?
--> list = temp;
Yes, it's this line:
list = temp;
All that does is copy the temp reference to the list reference. Now, both list and temp refer to your local list originally referred to by temp.
You'll want to add the contents of temp back to list instead.
list.addAll(temp);
list = temp just assigns a new value (the contents of temp) to the local variable named list - it does not change the object that list originally pointed to.
If you want to achieve such functionality, you could just re-add all the items in temp to list (after the while loop concludes, so you know it's empty):
list.addAll(temp);
The shuffle method receives a copy of a reference to your list. When you do list = temp; you're telling that reference to point to temp.
So you basically empty the list that is passed to the method and then you lose access to it.
Related
This question already has answers here:
Is there a way to access an iteration-counter in Java's for-each loop?
(16 answers)
Closed 3 years ago.
here Is Code there any way to get Index of the object from the list by calling a method in the list.
for example something like this:
class A{
String a="";
String b="";
}
List<A> alist= new ArrayList();
for (A a : alist) {
a.getIndexInList();
}
Why not use indexOf? If I recall correctly it is a built-in function of list.
List<A> alist= new ArrayList<>();
for (A a : alist) {
int index = alist.indexOf(a);
}
Only the list can give you the index. Unless the object in the array knows it's in an array it can't give you it's index.
There is no builtin solution, you can use external counter:
List<A> alist= new ArrayList();
int counter = 0;
for (A a : alist) {
// logic
counter++;
}
You could also create a map with indices as keys, something like:
IntStream.range(0, alist.size()).mapToObj(Integer::valueOf)
.collect(Collectors.toMap(
Function.identity(),
alist::get
));
but alist needs to be effectively final.
This question already has answers here:
Java ArrayList of ArrayList
(4 answers)
Closed 6 years ago.
List<List<Integer>> list = new LinkedList<List<Integer>>();
List<Integer> tmp = new LinkedList<Integer>();
tmp.add(2);
list.add(tmp);
tmp.add(3);
list.add(tmp);
The result of list is [[2,3],[2,3]]; I just confused about that why it is not [[2],[2,3]]. And when I use list.add(new LinkedList<Integer>(tmp)) it will work. I print tmp, it is still [2], [2,3], it is not changed. Why that happen?
Thank you in advance.
You added a reference to tmp to list. When you added it, tmp only contained [2,3]. After the addition to list, you added 3 to the same reference of tmp. This caused both "copies" to have [2,3].
One way could be to create a new list and do the following
tmp = new LinkedList<Integer>();
tmp.add(3);
list.add(tmp);
Now, list will look like [[2],[3]].
If you want list to be [[2],[2,3]]...
List<List<Integer>> list = new LinkedList<List<Integer>>();
List<Integer> tmp = new LinkedList<Integer>();
tmp.add(2);
// add a copy of this linkedlist to the "BIG" list
list.add(new LinkedList<Integer>(tmp));
tmp.add(3);
list.add(tmp);
let me know if something is not clear.
Java uses references to objects that you create with new to refer to those objects. In this example, the variable tmp is actually a reference to the LinkedList object on the heap.
Since list is a list of objects, it is actually a list of references to those objects. In this case, its two elements are references to the same heap object, tmp.
This question already has answers here:
Java ArrayList copy
(10 answers)
Closed 7 years ago.
I have an array list that stores objects called Movie. The objects contain variables such as name , date released ,genre etc.. Is there a way to duplicate the array so I can sort it one by one keep the original data unchanged. I will be displaying the data in text areas.
Use
List<Movie> newList = new ArrayList<>(existingList);
You can create a copy of the old ArrayList with:
List<Movie> newList = new ArrayList<Movie>(oldList);
You should know that this creates a shallow copy of the original ArrayList, so all of the objects in both lists will be the same, but the two lists will be different objects.
Though the question is ambiguous, you can use
List<Integer> newList = new ArrayList<Integer>(oldList); to copy an old List
and
Arrays.copyOf() to copy array.
System.arraycopy()
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
Source
You can get Array from original Array List as below:
Movie movieArray[] = arrayListMovie
.toArray(new Movie[arrayListMovie.size()]);
Every Collection Class provide a constructor to crate a duplicate collection Object.
List<Movie> newList = new ArrayList<Movie>(oldList);
since newList and oldList are different object so you can also create a clone of this object-
public static List<Movie> cloneList(List<Movie> oldList) {
List<Movie> clonedList = new ArrayList<Movie>(oldList.size());
for (Movie movie: oldList) {
clonedList.add(new Movie(movie));
}
return clonedList;
}
ArrayList is also dynamic array,but if you want to store this in array you can do this as-
int n=oldList.size();
Movie[] copiedArray=new Movie[n];
for (int i=0;i<oldList.size();i++){
copiedArray[i]=oldList.get(i);
}
This question already has answers here:
Convert list to array in Java [duplicate]
(11 answers)
Closed 8 years ago.
I have a created a LinkedList with an Employee object stored in it. I need to write a method convertToArray that would make an array of Employees by taking it from the LinkedList.
Any ideas?
The easiest way to do this is to utilize LinkedList.toArray method
// create an array and copy the list to it
Employee[] array = list.toArray(new Employee[list.size()]);
However, if you are just learning and would like to do this iteratively. Think about how you would declare and get all of the items into an array.
First, what do you need to do?
1) Declare the array of Employee's
In order to do that, you to know how big to make the array since the size of an array cannot be changed after declaration. There is a method inherited from List called .size()
Employee[] array = new Employee[list.size()]
2) For each slot in the array, copy the corresponding element in the list
To do this, you need to utilize a for loop
for(int i = 0; i < array.length; i++) {
//access element from list, assign it to array[i]
}
public <T> T[] convert (List<T> list) {
if(list.size() == 0 ) {
return null;
}
T[] array = (T[])Array.newInstance(list.get(0).getClass(), list.size());
for (int i=0;i<list.size();i++) {
array[i] = list.get(i);
}
return array;
}
Employee[] arr = new Employee[list.size()];
int i = 0;
for(Employee e : list) {
arr[i] = e;
i++;
}
This question already has answers here:
Converting 'ArrayList<String> to 'String[]' in Java
(17 answers)
Closed 4 years ago.
How can I convert a List to an Array in Java?
Check the code below:
ArrayList<Tienda> tiendas;
List<Tienda> tiendasList;
tiendas = new ArrayList<Tienda>();
Resources res = this.getBaseContext().getResources();
XMLParser saxparser = new XMLParser(marca,res);
tiendasList = saxparser.parse(marca,res);
tiendas = tiendasList.toArray();
this.adaptador = new adaptadorMarca(this, R.layout.filamarca, tiendas);
setListAdapter(this.adaptador);
I need to populate the array tiendas with the values of tiendasList.
Either:
Foo[] array = list.toArray(new Foo[0]);
or:
Foo[] array = new Foo[list.size()];
list.toArray(array); // fill the array
Note that this works only for arrays of reference types. For arrays of primitive types, use the traditional way:
List<Integer> list = ...;
int[] array = new int[list.size()];
for(int i = 0; i < list.size(); i++) array[i] = list.get(i);
Update:
It is recommended now to use list.toArray(new Foo[0]);, not list.toArray(new Foo[list.size()]);.
From JetBrains Intellij Idea inspection:
There are two styles to convert a collection to an array: either using
a pre-sized array (like c.toArray(new String[c.size()])) or
using an empty array (like c.toArray(new String[0]). In
older Java versions using pre-sized array was recommended, as the
reflection call which is necessary to create an array of proper size
was quite slow. However since late updates of OpenJDK 6 this call
was intrinsified, making the performance of the empty array version
the same and sometimes even better, compared to the pre-sized
version. Also passing pre-sized array is dangerous for a concurrent or
synchronized collection as a data race is possible between the
size and toArray call which may result in extra nulls
at the end of the array, if the collection was concurrently shrunk
during the operation. This inspection allows to follow the
uniform style: either using an empty array (which is recommended in
modern Java) or using a pre-sized array (which might be faster in
older Java versions or non-HotSpot based JVMs).
An alternative in Java 8:
String[] strings = list.stream().toArray(String[]::new);
Since Java 11:
String[] strings = list.toArray(String[]::new);
I think this is the simplest way:
Foo[] array = list.toArray(new Foo[0]);
Best thing I came up without Java 8 was:
public static <T> T[] toArray(List<T> list, Class<T> objectClass) {
if (list == null) {
return null;
}
T[] listAsArray = (T[]) Array.newInstance(objectClass, list.size());
list.toArray(listAsArray);
return listAsArray;
}
If anyone has a better way to do this, please share :)
I came across this code snippet that solves it.
//Creating a sample ArrayList
List<Long> list = new ArrayList<Long>();
//Adding some long type values
list.add(100l);
list.add(200l);
list.add(300l);
//Converting the ArrayList to a Long
Long[] array = (Long[]) list.toArray(new Long[list.size()]);
//Printing the results
System.out.println(array[0] + " " + array[1] + " " + array[2]);
The conversion works as follows:
It creates a new Long array, with the size of the original list
It converts the original ArrayList to an array using the newly created one
It casts that array into a Long array (Long[]), which I appropriately named 'array'
This is works. Kind of.
public static Object[] toArray(List<?> a) {
Object[] arr = new Object[a.size()];
for (int i = 0; i < a.size(); i++)
arr[i] = a.get(i);
return arr;
}
Then the main method.
public static void main(String[] args) {
List<String> list = new ArrayList<String>() {{
add("hello");
add("world");
}};
Object[] arr = toArray(list);
System.out.println(arr[0]);
}
For ArrayList the following works:
ArrayList<Foo> list = new ArrayList<Foo>();
//... add values
Foo[] resultArray = new Foo[list.size()];
resultArray = list.toArray(resultArray);
Example taken from this page: http://www.java-examples.com/copy-all-elements-java-arraylist-object-array-example
import java.util.ArrayList;
public class CopyElementsOfArrayListToArrayExample {
public static void main(String[] args) {
//create an ArrayList object
ArrayList arrayList = new ArrayList();
//Add elements to ArrayList
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
arrayList.add("5");
/*
To copy all elements of java ArrayList object into array use
Object[] toArray() method.
*/
Object[] objArray = arrayList.toArray();
//display contents of Object array
System.out.println("ArrayList elements are copied into an Array.
Now Array Contains..");
for(int index=0; index < objArray.length ; index++)
System.out.println(objArray[index]);
}
}
/*
Output would be
ArrayList elements are copied into an Array. Now Array Contains..
1
2
3
4
5
You can use toArray() api as follows,
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("ListItem1");
stringList.add("ListItem2");
String[] stringArray = new String[stringList.size()];
stringArray = stringList.toArray(stringList);
Values from the array are,
for(String value : stringList)
{
System.out.println(value);
}
This (Ondrej's answer):
Foo[] array = list.toArray(new Foo[0]);
Is the most common idiom I see. Those who are suggesting that you use the actual list size instead of "0" are misunderstanding what's happening here. The toArray call does not care about the size or contents of the given array - it only needs its type. It would have been better if it took an actual Type in which case "Foo.class" would have been a lot clearer. Yes, this idiom generates a dummy object, but including the list size just means that you generate a larger dummy object. Again, the object is not used in any way; it's only the type that's needed.
Try this:
List list = new ArrayList();
list.add("Apple");
list.add("Banana");
Object[] ol = list.toArray();