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.
Related
When I create a Java list and I want that the head is a list, should it print a [[-1,0],1,2,3,4] or its alright it just leave the sublist [-1, 0] as two separated elements like [-1, 0, 1, 2,3,4] and, how can I get the first structure as an aswer.
From your post I guess you are asking about how to create a list "construct" in Java which contains both list and non-list elements.
In Java all elements of your list/array need to have the same type. In the example you posted ([[-1,0],1,2,3,4]), the elements are not all the same type. What you have is this: [List<Integer>, Integer, Integer, Integer, Integer]. The first one is different, which isn't allowed in Java.
So, what you need to do is make it so that all elements of your list/array are the same type.
For your case, where there are only integers in your list, the easiest thing to do is to change your types to this: [List<Integer>, List<Integer>, List<Integer>, List<Integer>, List<Integer>] (with your specific values: [[-1,0],[1],[2],[3],[4]]). Instead of a list of List<Integer> and Integer, you now have a list containing only List<Integer> (some of your lists happen to contain only 1 element, but that is ok).
This is called a "two-dimensional list" and depending on whether you want to code it with arrays or java.util.Lists you can code it in one of the following ways:
// with arrays
int[] myTwoDarr = int[5][];
myTwoDarr[0] = new int[]{-1, 0};
myTwoDarr[1] = new int[]{1};
myTwoDarr[2] = new int[]{2};
myTwoDarr[3] = new int[]{3};
myTwoDarr[4] = new int[]{4};
// With Lists
List<List<Integer>> myList = new LinkedList<>();
List<Integer> nestedList1 = new LinkedList<>();
nestedList.add(-1);
nestedList.add(0);
myList.add(nestedList1);
List<Integer> nestedList2 = new LinkedList<>();
nestedList2.add(1);
myList.add(nestedList2);
...etc...
Now, if you absolutely must have different kinds of data in your list, you can create a list of Object instead.
In Java Object is a type from which all non-primitive types inherit. Thus, as long as something is not a primitive, it is an Object and can go in a list of Object. This will allow you to put any kind of data in the elements of your list. Using Object allows you to have a list of all the same type which looks like this: [Object, Object, Object, Object, Object]. But, now Java does not know the specific types you actually have stored in your elements so you will need to type cast when getting them.
Here's an example using a java.util.List:
List<Object> myList = new LinkedList<>();
List<Integer> nestedList = new LinkedList<>();
nestedList.add(-1);
nestedList.add(0);
myList.add(nestedList);
myList.add(1);
myList.add("a string");
// You need to cast when taking elements out of the list.
List<Integer> newNest = (List<Integer>) myList.get(0);
Integer myInt = (Integer) myList.get(1);
String myString = (String) myList.get(2);
Since all your base data types are the same (Integer/int) I recommend avoiding the Object list method and going with the 2D list. It's simpler and less error prone to not do all this casting.
If I can declare an Array of FloatLists: FloatList [][] values = new FloatList[3][3];
Why doesn’t it work to declare an Array of ArrayLists holding FloatLists like this: ArrayList<FloatList> [][] values = new ArrayList<FloatList>() [3][3];? OR EVEN: ArrayList<FloatList> [][] values = new ArrayList<FloatList> [3][3]();
How can this be achieved? Will it be hard to refer to the floats buried deep under its crusty texture?
Work from the inner-most type to the outer-most type. You start with FloatList:
FloatList
Then wrap that in an ArrayList:
ArrayList<FloatList>
Then you want an array of that:
ArrayList<FloatList>[]
Or a 2D array:
ArrayList<FloatList>[][]
That gives you the type for the declaration, but then you have to initialize the variable by giving it a value. Start with the array by giving it a size:
ArrayList<FloatList>[] array = new ArrayList[10];
This gives you an array of ArrayList<FloatList> objects, but they start out as null. To give them a value, you'd loop over every index in the array and use the new keyword to set the value of the index to an instance of ArrayList<FloatList>:
for(int i = 0; i < array.length; i++){
array[i] = new ArrayList<FloatList>();
}
For a 2D array, you'd use the same logic, just in a nested for loop.
Then to add a FloatList to an ArrayList at a specific index of the array, you'd do this:
array[i].add(new FloatList());
Finally, to add a float to a FloatList in an ArrayList at an index in the array, you'd do this:
array[x].get(y).append(0.5);
And to get a float out of an index in the FloatList in an ArrayList at an index in the array, you'd do this:
float f = array[x].get(y).get(z);
Putting it all together, it looks like this:
ArrayList<FloatList>[] array = new ArrayList[10];
for(int i = 0; i < array.length; i++){
array[i] = new ArrayList<FloatList>();
}
array[1].add(new FloatList());
array[1].get(0).append(0.25);
array[1].get(0).append(0.5);
array[1].get(0).append(0.75);
float f = array[1].get(0).get(2);
println(f);
ArrayList<FloatList> [][] values = new ArrayList[3][3];
Basically, you're declaring that you want an object that is a 3D array of ArrayLists, and not generating actual ArrayList objects.
Afterwards, you have to instantiate each of them, so for example:
values[0][0] = new ArrayList<>();
And so on.
It doesn't work because of the way the JVM provides Generics. Generics in Java is a front-end compiler feature that becomes raw type usages and casts at execution time.
What is the compiler doing when I use generics?
Here's a terribly-contrived example. Let's say I want to create a List<String> to store command line arguments that I will later use to kick off a new process with, like so:
List<String> cmd = new ArrayList<>();
cmd.add("java");
cmd.add("-jar");
cmd.add("path/to/my.jar");
...
String args = cmd.get(0)+" "+cmd.get(1)+" "+cmd.get(2);
At compile time, the compiler will check to make sure that I am using the String type every time I use a generic List method via cmd and throw an error if I try to use instances of an incompatible type. However, there's a little thing called erasure that happens during compilation, before execution. Effectively, under the hood, the compiler converts the code above into something like this:
List cmd = new ArrayList();
cmd.add("java");
cmd.add("-jar");
cmd.add("path/to/my.jar");
...
String args = (String)cmd.get(0)+" "+(String)cmd.get(1)+" "+(String)cmd.get(2);
So why doesn't my generic array code compile?
In your example, you wanted to create an array of a generic type, like so:
ArrayList<FloatList>[][] array = new ArrayList<FloatList>[n][m]; //Doesn't compile? What gives?
The problem is, because of type erasure, the ArrayList<FloatList> class type doesn't really exist, and now you've asked the JVM to create a 2-dimensional array of that non-existent type.
Okay, so what's the alternative?
Well ... it isn't pretty, but you could do something like this:
class ArrayListOfFloatList extends ArrayList<FloatList>{
...
}
//Somewhere else in your code:
ArrayListOfFloatList[][] myArray = new ArrayListOfFloatList[n][m];
//This will compile because ArrayListOfFloatList is a real class.
The only other way around this would be to not use arrays. Ugly, perhaps, but it's unfortunately a limitation of how Java is currently implemented.
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.
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.
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]);
}