Converting LinkedList to Arrary [duplicate] - java

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++;
}

Related

How to get index of List Object [duplicate]

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.

Convert ArrayList to Int [] array using .toArray()? Or...?

So, this is part of a method which checks for available rooms within a date range and is meant to return the int [] array of room numbers which are available.
ArrayList roomNums = new ArrayList();
roomNums.toArray();
for (Room room: rooms){
int roomNumber = room.getRoomNumber();
if(room.getRoomType() == roomType && isAvailable(roomNumber, checkin, checkout)){ // This works fine, ignore it
roomNums.add(roomNumber);
}
}
return roomNums.toArray(); // Error here, return meant to be int [] type but it's java.lang.Obeject []
The error occurs at the end at roomNums.toArray()
I saw someone else do this one liner and it worked for them, why is it not for me?
Every element in roomNums is an integer. (I think)
What's the quickest and easiest way to print an integer array containing the available rooms? Do I need to make a loop or can I do something with this .toArray() one liner or something similar to it?
Thanks
Don't use raw types. Replace ArrayList roomNums = new ArrayList(); with
ArrayList<Integer> roomNums = new ArrayList<>();
Then return it as Integer[]
roomNums.toArray(Integer[]::new);
If you need primitive array, then it can be done with stream:
return roomNums.stream().mapToInt(Integer::valueOf).toArray();
See also How to convert an ArrayList containing Integers to primitive int array?
Unfortunately, you will need to use Integer[] if you want to use toArray
List<Integer> roomNums = new ArrayList<>();
// code here
Integer[] arr = new Integer[roomNums.size()];
return roomNums.toArray (arr);
However you can still do it manually like
List<Integer> roomNums = new ArrayList<> ();
// code here
int[] arr = new int[roomNums.size()];
for (int i = 0; i < arr.length; i++)
arr[i] = roomNums.get (i);
return arr;
As mentioned above use the ArrayList to hold your values:
ArrayList<Integer> roomNums = new ArrayList<>();
then you can use the object super class to convert to array
Object[] numbersArray = roomNums.toArray();
then just continue running the for loop and your program

Own Shuffle Method Doesn't Work in Java [duplicate]

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.

Array list intValue()

Hey i have an array list of numbers and when i try to convert into int i get The method intValue() is undefined for the type Object error. This is the code snippet.
while (1>0) {
a = Integer.parseInt(in.next());
if(a == -999)
break;
else {
list.add(a);
i++;
}
}
int j;
int[] array = new int[list.size()];
for(j=0;j<list.size();j++) {
array[j] = list.get(j).intValue();
}
It seems you have created a list of objects and not Integers. Hence when you call intValue then it says that there is no such method for type Object. I would recommend that you define your list as list of Integers using generics. Here is the sample:
List<Integer> list = new ArrayList<Integer>();
If you don't do so then you list created will hold the items of class Object. And then you need to cast the object fetched from the list everytime to Integer.

Convert list to array in Java [duplicate]

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();

Categories