Cast an Arraylist of Doubles to ArrayList of Integers - java

I am trying to convert an ArrayList to ArrayList. I am having actually a list of labels in Double and I want to create a list of Integers. I am trying to add the one to another but of course I need a casting process.
ArrayList<Integer> lab = new ArrayList<Integer>();
lab.addAll(labels.data); //labels.data is an Arraylist of Doubles.
How can I cast one list to another??
I ve tried this to add one by one:
ArrayList<Integer> lab = new ArrayList<Integer>();
for (int i = 0; i < labels.data.size(); i++) {
lab.set(i, labels.data.get(i).intValue());
}
But I received outOfBoundsError.

You can not convert List<Double> to List<Integer> directly. Loop on each Double object and call intValue() function to get the integer part of it. For e.g. 13.3 will give 13. I hope thats what you want.
for(Double d : labels.data){
lab.add(d.intValue());
}

First, is there any need for this to be an ArrayList particularly, or for these to be the wrapper classes instead of the primitives? If not, working with a simple array will avoid the overhead of boxing and unboxing, and of storing a lot of objects.
That aside, you'd probably want to loop over the list and cast each item to a double (or a Double), then add it to a new array (or ArrayList). There isn't a bulk operation for this.

You are getting outOfBoundsError because you are using set() instead of add(). set() is a replacement command and requires there to already be an object in that position.

Use Arraylist<Number>. A Number is a parent of both Double and Integer, so you would be able to add Doubles to your list and the Number.intValue() will convert (autoboxing) into Integer when required.
ArrayList<Number> list;
list.add(new Double(17.7));
Integer i = list.get(0).intValue(); // 18, rounding.

Related

Initialize ArrayList with doubles

I'm trying to initialize an ArrayListto use later in my code, but it seems like it doesn't accept doubles.
public ArrayList<double> list = new ArrayList<double>();
It gives an error under 'double', sayin "Syntax error on token "double", Dimensions expected after this token"
An ArrayList doesn't take raw data types (ie, double). Use the wrapper class (ie, Double) instead :
public ArrayList<Double> list = new ArrayList<>();
Also, as of Java 7, no need to specify that it's for the Double class, it will figure it out automatically, so you can just specify <> for the ArrayList.
You need to use the Wrapper class for double which is Double. Try
public ArrayList<Double> list = new ArrayList<Double>();
In Java, ArrayLists (and other generic classes) only accept object references as types, not primitive data types. There are wrapper classes that allow you to emulate using primitives, though: Boolean, Byte, Short, Character, Integer, Long, Float and Double;
public ArrayList<Double> list = new ArrayList<Double>();
//or "public ArrayList<Double> list = new ArrayList<>();" in Java 1.7 and beyond
Values inside are "autoboxed" and "autounboxed" so you can treat doubles as Doubles without problems, and vice versa. You may need to explicitly specify whether you want arguments to be treated as int or Integer when dealing with lists of integral types, though, to disambiguate between cases like remove(int index) and remove(Object o).
public ArrayList<Double> doubleList = new ArrayList<>();
From Java 1.7, you don't need to write Double while initializing ArrayList, so it's your choice to write Double in new ArrayList<>(); or new ArrayList<Double>(); or not.. otherwise it's not compulsory.
Also known as a dynamic array.
No need to pre-determine the number of elements up
front, just add to the array as we need it

adding in ArrayList without iterating

I want to create an ArrayList<Float> of length 350. I did this:
x = new ArrayList<Float>(350);
No i want this array to have 'zero' float value at each point. i can do this:
for (int i = 0; i< 350 ; i++){
x.add((float) 0.0);
}
So my question is if there is another way to do the same thing without iterating. I want minimum iterating to increase efficiency.
If you want efficiency I wouldn't use ArrayList or Float here. I wouldn't recommend using float even as it's precision is so poor, unless you really know what you are doing.
I suggest you use an array of double.
double[] x = new double[350]; // all 0.0
java's Collections class has a nice utility for this: nCopies. Note that this creates an immutable list, but it does exactly what you want :)
From java documentation:
ArrayList(int initialCapacity)
Constructs an empty list with the specified initial capacity.
Note the list is still empty so you have to add the elements one by one. Only capacity is changed.
I would advice you to construct another collection for instance an array and then initialize the list using that constructor:
ArrayList(Collection<? extends E> c)
Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.
As Peter says use an array. If you want this in an array list you can use the code below. This creates an arraylist of 100 integers each with a value of 42
Integer[] a = new Integer[100];
Arrays.fill(a, 42);
List<Integer> l = new ArrayList<Integer>(Arrays.asList(a));
for (Integer integer : l) {
System.out.println(integer);
}
You can modify it easily to be of type Float and assign any initial value you want.

Java - Casting, Generics, Objects and Arrays

I was wondering if it is possible to convert an Object into something else.
I have a Object which contains a series of numbers in a random order such as: 3, 4, 2, 5, 1 and wondering if I am able to turn it into an int[] or select certain elements from it, as in a number from the sequence?
EDIT:
so some of the code i have is:
//This contains all the different combinations of the numbers
ArrayList routePop4 = new ArrayList();
//This picks out the first one, just as a test
Object test = routePop4.get(0);
But the idea is that I want to loop through each element of test.
An Object cannot "contain a series of numbers". However many subclasses of Object, such as all of the Collections can "contain a series of numbers", and they come with a toArray() method to turn the contents of the collection into an array.
If you have a collection, but only have access to it as an Object, you need to cast it before you can work with it properly:
ArrayList<Integer> list = (ArrayList<Integer>)test;
Integer[] arr = list.toArray(new Integer[]{});
It's fairly rare in day-to-day Java to actually be working with variables cast as Object, if you are, it should be a red flag that you may be doing something wrong. You can use generics to allow objects that contain other objects to do so generically, like so:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1); // Can only add integers, list.add("a string") would fail at compile time
int n = list.get(0); // no need to cast, we know list only contains Integers
If you aren't using a Collection, you'll presumably need to roll your own, as Luke Taylor's answer suggests. That said, you'll get better answers if you can provide more information, the current text of your question doesn't make sense in a Java context.
After seeing your edit, I recommend taking advantage of generics.
When you declare an ArrayList you can indicate what kind of objects it's going to contain.
For example, if you know your ArrayList will contain Strings, you would do this:
List<String> myList = new ArrayList<String>();
If each element of your list is an array of Integers, you would do this:
List<Integer[]> listOfIntegerArrays = new ArrayList<Integer[]>();
Then you could get any element from your list and assign it to an Integer array like this:
Integer[] integerArray = listOfIntegerArrays.get(0);
Then you could iterate over every Integer in the list like this:
for (Integer loopInteger : integerArray) {
System.out.println("The value: " + loopInteger);
}
Some more reading on generics:
http://thegreyblog.blogspot.com/2011/03/java-generics-tutorial-part-i-basics.html
http://docs.oracle.com/javase/tutorial/java/generics/
You could do something like this:
int[] numbersFromObject = new int[yourObject.getAmountOfNumbers()];
// Initialize array with numbers from array
for(int i = 0; i < yourObject.getAmountOfNumbers(); i++) {
numbersFromObject[i] = yourObject.getNumber(i);
}
I'm not sure what methods your object contains, yet I'm sure you'll be able to adjust to the following mentioned above.
I hope this helps.

List of Arrays in Java

What is the syntax for making a List of arrays in Java?
I have tried the following:
List<int[]> A = new List<int[]>();
and a lot of other things.
I need to be able to reorder the int arrays, but the elements of the int arrays need not to be changed. If this is not possible, why?
Thank you.
Firstly, you can't do new List(); it is an interface.
To make a list of int Arrays, do something like this :
List<int[]> myList = new ArrayList<int[]>();
P.S. As per the comment, package for List is java.util.List and for ArrayList java.util.ArrayList
List<Integer[]> integerList = new ArrayList<Integer[]>();
Use the object instead of the primitive, unless this is before Java 1.5 as it handles the autoboxing automatically.
As far as the sorting goes:
Collections.sort(integerList); //Sort the entire List
and for each array (probably what you want)
for(Integer[] currentArray : integerList)
{
Arrays.sort(currentArray);
}
List is an interface, not a class. You have to choose what kind of list. In most cases an ArrayList is chosen.
List a = new ArrayList();
You've mentioned that you want to store an int array in it, so you can specify the type that a list contains.
List<int[]> a = new ArrayList<int[]>();
While you can have a collection (such as a list) of "int[]", you cannot have a collection of "int". This is because arrays are objects, but an "int" is a primitive.

How to convert an int[] array to a List?

I expected this code to display true:
int[] array = {1, 2};
System.out.println(Arrays.asList(array).contains(1));
The method Arrays.asList(T ...) is, when generics are erased and varargs are transformed, actually equal to a method of type Arrays.ofList(Object[]) (which is the, binary equivalent, JDK 1.4 version of the same Method).
An array of primitives is an Object (see also this question), but not an Object[], so the compiler thinks you are using the varargs version and generates an Object array around your int array. You could illustrate what's happening by adding an extra step:
int[] array = {1, 2};
List<int[]> listOfArrays = Arrays.asList(array);
System.out.println(listOfArrays.contains(1));
This compiles and is equivalent to your code. It also obviously returns false.
The compiler translates varargs calls into calls with a single array, so calling a varargs method that expects parameters T ... with parameters T t1, T t2, T t3 is equivalent to calling it with new T[]{t1, t2, t3} but the special case here is that varargs with primitives will be autoboxed before the array is created if the method needs an object array. So the compiler thinks the int array is passed in as a single Object and creates a single element array of type Object[], which it passes to asList().
So here's the above code once again, the way the compiler implements it internally:
int[] array = {1, 2};
// no generics because of type erasure
List listOfArrays = Arrays.asList(new Object[]{array});
System.out.println(listOfArrays.contains(1));
Here are some good and bad ways to call Arrays.asList() with int values:
// These versions use autoboxing (which is potentially evil),
// but they are simple and readable
// ints are boxed to Integers, then wrapped in an Object[]
List<Integer> good1 = Arrays.asList(1,2,3);
// here we create an Integer[] array, and fill it with boxed ints
List<Integer> good2 = Arrays.asList(new Integer[]{1,2,3});
// These versions don't use autoboxing,
// but they are very verbose and not at all readable:
// this is awful, don't use Integer constructors
List<Integer> ugly1 = Arrays.asList(
new Integer(1),new Integer(2),new Integer(3)
);
// this is slightly better (it uses the cached pool of Integers),
// but it's still much too verbose
List<Integer> ugly2 = Arrays.asList(
Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3)
);
// And these versions produce compile errors:
// compile error, type is List<int[]>
List<Integer> bad1 = Arrays.asList(new int[]{1,2,3});
// compile error, type is List<Object>
List<Integer> bad2 = Arrays.asList(new Object[]{1,2,3});
Reference:
Java Tutorial > Classes and Objects > Passing Information to a Method or a Constructor > Varargs
Arrays.asList(T ...)
But to actually solve your problem in a simple way:
There are some library solutions in Apache Commons / Lang (see Bozho's answer) and in Google Guava:
Ints.contains(int[], int) checks whether an array of ints contains a given int
Ints.asList(int ...) creates a List of Integers from an int array
The Arrays.asList(array) will result in a singleton list of an int[].
It works as you expect if you change int[] to Integer[]. Don't know if that helps you though.
Arrays.asList(ArrayUtils.toObjectArray(array))
(ArrayUtils is from commons-lang)
But if you want to just call contains there is no need of that. Simply use Arrays.binarySearch(..) (sort the array first)
This
System.out.println(Arrays.asList(array).contains(array));
returns true.
It seems like your understanding of Arrays.asList(T... a) is wrong. You wouldn't be the first person to make an assumption as to how it works.
Try it with
System.out.println(Arrays.asList(1, 2).contains(1));
Autoboxing just doesn't work the way you want it to in this case. The following code may be a bit verbose, but does the job of converting an int array to a list:
List<Integer> list = new ArrayList<Integer>(array.length);
for (int value : array) {
list.add(value);
}
The following code displays true:
Integer[] array = {1, 2};
System.out.println(Arrays.asList(array).contains(1));
(Your version fails, since Int's not beeing objects, but Int[] is an object. Therefor you will call asList(T... a) with one element beeing a Collection, since it is not possible to have an Collection a.)
When you call
Arrays.asList(array)
on your array of primitives, you get a List instance containing one object: an array of int values! You have to first convert the array of primitives into an array of objects, as #Bozho suggests in his answer.
If you only want to check whether the array contains certain element just iterate over array and search for element. This will take o(n/2). All other solutions are less effective. Any method that copies array to list must iterate over array and therefore this operation only requires n atomic assignments.
I dont think there is a method call you could use. Try it like this
List<Integer> list = new ArrayList<Integer>();
for (int index = 0; index < array.length; index++)
{
list.add(array[index]);
}

Categories

Resources