Java 2D Int Arraylist - java

I dont quite understand what is the problem with the second declaration.
// Compiles fine
ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
// error (Unexpected type, expected -reference ,found :int)
ArrayList<ArrayList<int>> intarray = new ArrayList<ArrayList<int>>();

ArrayList is an implementation of List<T>, your problem is that you are trying to create an arraylist of int, its impossible since int is not an object. using Integer will solve your problem.
ArrayList<ArrayList<Integer>> intarray = new ArrayList<ArrayList<Integer>>();

The way generics work is simple. The header of List looks a little like this:
public interface List<T>
Where T is some Object. However, int is not a subclass of Object. It is a primitive. So how do we get around this? We use Integer. Integer is the wrapper class for int. This allows us to use int values in a List, because when we add them, they get auto boxed into Integer.
Primitive types are actually scheduled for deprecation in Java 10. Taken from Wikipedia:
There is speculation of removing primitive data types, as well as moving towards 64-bit addressable arrays to support large data sets somewhere around 2018.
Just a Note on your Code
In Java, the convention is to have the declaration using the most generic type and the definition using the most specific concrete class. For example:
List myList;
// List is the interface type. This is as generic as we can go realistically.
myList = new ArrayList();
// This is a specific, concrete type.
This means that if you want to use another type of List, you won't need to change much of your code. You can just swap out the implementation.
Extra Reading
Read about Wrapper Classes.
Read about Auto Boxing and Unboxing.
Read about Primitive Types.

You can only make List of Objects. int is a primitive type.
Try use:
ArrayList<ArrayList<Integer>> intarray = new ArrayList<ArrayList<Integer>>();

You must create an ArrayList<Integer> not an ArrayList<int>
A class(Arraylist in your case) can be a type of a CLASS (Integer)

ArrayList does not except primitive types as an argument. It only accepts Object types you should use:
ArrayList<ArrayList<Integer>> intArray = new ArrayList<ArrayList<Integer>>();

Related

Why autoboxing is not supporting in collection.toArray() in java

Is there no any short cut to do this nicely?
That ugly two loops (One loop to read the pmList and second loop to add to the markupArray) is the only option (Instead of ArrayUtils).
ArrayList<Double> pmList = new ArrayList<Double>();
pmList.add(0.1); // adding through a loop in real time.
pmList.add(0.1);
pmList.add(0.1);
pmList.add(0.1);
double[] markupArray = new double[pmList.size()];
arkupArray = pmList.toArray(markupArray); // This says The method toArray(T[]) in the type ArrayList<Double> is not applicable for the arguments (double[])
Simply use a Double[] array, instead of double[] then everything works fine. If you know the size of the list ahead of time, you can also skip the list and insert directly into the array. It might even be worth to traverse the input two times: Once for retrieving its size and once for insertion.
Auto boxing only works for primitive types, not for arrays of primitive types. A double[] array is no T[] array, since a type parameter T must always be an Object. While a double may be autoboxed to T (with T=Double), a double[] cannot be autoboxed to T[].
The reason why arrays are not autoboxed is probably that this operation would be very costly: Boxing an array means creating a new array and boxing each element. For large arrays, this has a huge performance hit. You don't want such a costly operation to be done implicitly, hence no autoboxing for arrays. In addition, boxing a complete array would yield a new array. Thus, when writing to the new array, the changes would not write through to the old array. So you see, there are some semantics problems with array-boxing, so it is not supported.
If you must return a double[] array, then your must either write your own function or use a third-party library like Guava (see msandiford's answer). The Java Collections framework has no methods for (un)boxing of arrays.
You could use TDoubleArraList or guava's primitive list collection.
You could also determine the size in advance in one loop and add the values in another.
Why not make your own shortcut?
static double[] doubleListToArray(List<Double> list) {
int k = 0;
double[] result = new double[list.size()];
for(double value : list)
result[k++] = value;
return result;
}
Google guava has Doubles#asList(...) and Doubles#toArray(...) which provide conversions from double[] to List<Double> and from Collection<? extends Number> to double[] respectively.
You are right that this is not very intuitive at first look. However, this limitation is related to the way the Java language implements generic types and auto-boxing:
Generic types are erased at runtime. This implies that any ArrayList<Double> is represented by a single compiled Java class ArrayList which is shared with other generic representations of ArrayList such as for example ArrayList<String>. As a consequence, the compiled method ArrayList::toArray does not (and must not) know what generic type an instance represents as the single compiled method must be applicable for any generic type. As the elements could therefore be anything like String or Double, you need to provide an array to the method. The method can then check the type of the target array at runtime and check the elements that are filled into the array at runtime to be assignable to the array's component type. All this logic can be implemented by a single compiled method.
Secondly, auto-boxing and -unboxing is something that only exists at compile time. This means that the statements
Integer i = 42;
int j = i;
are compiled as if you wrote
Integer i = new Integer(42);
int j = i.intValue();
It is the Java compiler that adds the boxing instructions for you. The Java runtime applies a slightly different type system where boxing is not considered. As a consequence, the single compiled method ArrayList::toArray that we mentioned in (1) cannot know that this boxing needs to be applied as we argued that the method must be applicable for any type T which might not always represent a Double.
In theory, you could alter the implementation of ArrayList::toArray to explicitly checks if an array's component type and a lists element type are applicable for unboxing but this approach would result in several branches which would add quite a runtime overhead to the method. Rather, write a small utility method that specializes on the Double type and applies the implicit unboxing due to the specialization. An iteration over all list items suffices for this purpose, this is how the ArrayList::toArray is implemented as well. If your array is small, consider to use an array of boxed values Double[] instead of double[]. If your array is however large, lives long or you are restrained to primitive types in order to comply to a third-party API, use the utility. Also, look out for implementations of primitive collections if you want to ungo the overall boxing. With Java 8, use a Stream in order to inline the array conversion.

What is the error Java ArrayLists

I am throughly convinced that this is snippet of code has an error. The Java from the ground up programming book says that there is no error. This is the code:
ArrayList temp = new ArrayList();
temp.add("35");
temp.add(35);
Isn't there an error with line 2? An arrayList cannot have a string and an integer within the same ArrayList correct? Please correct me if I am wrong, I have a test on this tomorrow. Thank you all in advance!
Yes, it is correct.
Since you haven't declared any type in ArrayList it allow all Objects.
Now your ArrayList as same as
ArrayList<Object> temp = new ArrayList<Object>();
And see below examples
ArrayList<String> temp = new ArrayList<String>();
temp.add("35");
temp.add(35); //compiler error, Only Strings please
see below example
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add("35");//compiler error, Only Integers please
temp.add(35);
And it's highly discouraged to use Raw types, Always prefer to use with specific type.
Now in first case ArrayList temp = new ArrayList();, when you return it returns an Object which is unkown type. It may be an Integer or a String, you need to check it manually after you got it back from List
ArrayList temp = new ArrayList(); There is no issue here. This is an ArrayList which will accept any data type since it is not defined specific data type (raw ArrayList).
it is correct because its a raw type means you can add any object.You can add anything that extends Object class
you can write temp.add(x); where x can be any thing String,int,long Date anything that extends Object
example
String x="";
int x1=1;
Date df=new Date();
temp.add(x);// will work
temp.add(x1);//will work
temp.add(df);// will work
yes your array list can hold both String and integer.
but array list only store objects String and Integer objects it doesnt support int primitive datatypes only objects inside arraylist
ArrayList<Object> arr=new ArrayList<>();
String s="35";
Integer in=35;
arr.add(in);
arr.add(s);`
It is correct. Since you haven't declare any type for list, it treats all the elements as Object class. Your definition is
ArrayList<Object> arr=new ArrayList<>();
for compiler. In this case 35 will be boxed to Integer and "35" will be a String. Both Integer and String are subclass of Object and there wan't be any compile time error.
In java there is something named as Generics which allows programmers to abstract over types.
Arraylist code internally uses it.So when you don't define any generic type the default type it takes is the Object class type.
And as String as well as Integer both are subclasses of Object class, so this operation is allowed according to OOPs.

Interpreting JAVA Command

I am in a data structures class and have had about a year and half of experience with JAVA. I am trying to understand code which is not clearly defined in the book. In the following line:
Queue<Integer> encodingQueue = new LinkedList<Integer>();
I understand that we are creating a new LinkedList object of Queue type. My questions are:
what is the <> used with Integer for? And why is it also with the LinkedList object and not in the parameters?
Why is the word Integer used and not int?
Thanks!
good luck in your data structures class!
Generics
In Java, these data structures (i.e. Queue, LinkedList, ...) can hold any kind of object. More often than not, though, a given instance of a Queue or LinkedList will hold a collection of the same type (here integers).
The angle-bracket syntax is used to specify which types are allowed in this specific instance of the collection.
So, the way to read:
Queue<Integer> encodingQueue = new LinkedList<Integer>();
is...
"Create a new linked-list that holds only integers, and assign that instance to the reference variable 'encodingQueue' which will be treated like a queue that holds only integers."
This feature that you're using is called "Generics". You can read up more about it here: http://en.wikipedia.org/wiki/Generics_in_Java
Autoboxing
In Java, there are two kinds of types: primitives and object references. "int" is a primitive and "Integer" is a class.
You cannot create a reference to a primitive in Java and collections (like LinkedList) only hold object references. So, you cannot stuff a primitive into a collection (e.g. you cannot put "int"s into a LinkedList). This is why Java provides the object equivalent for primitives: so that you can create collections of things like integers, floats, booleans, etc.
It can be a little confusing when you first start using primitives; Java will attempt to automatically convert primitives to object references when that's what's clearly needed (and vice-versa). This feature is called "autoboxing".
List myList = new LinkedList<Integer>();
myList.add(2);
Here, 2 is a primitive. But the compiler knows that you need an object reference, not a primitive. So, it automatically "boxes-up" this value by (in the background) creating a new instance of the class Integer and setting it's value to 2.
So, that's equivalent to (and this is what actually happens):
List myList = new LinkedList<Integer>();
myList.add(Integer.valueOf(2));
Where Integer.valueOf() first looks in an internal cache to see if an instance already exists for that value. If it does, that's returned, otherwise a new Integer object for that value is created. (Thank you, Boris, for pointing this out)
http://docs.oracle.com/javase/tutorial/java/generics/
Used to specify type parameters. It's how you pass a type into a class. Lists/queues have them, because it's the type of Object that the list holds.
Integer is used instead of int because ints are not Objects. Integer is just the wrapper class for it.
Integer is a object based wrapper version of the primitive 'int'. This allows the basic type to play well in object oriented language. Read more here:
They can be used interchangably native and wrapper, this is called 'autoboxing/unboxing'
http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html
The <> are part of Java Generics (A way to tell the compiler what object you expect to work with), more here:
http://docs.oracle.com/javase/tutorial/java/generics/
Happy learning!
That infers the type of object to be stored in the Queue. You'll want to look into Java Generics.
Collections store objects, int is a primitive type, Integer is the Java object representation. The compiler will autobox any ints you attempt to put in the Queue as Integers.
1) <Integer> is used to specify at compile-time that the objects contained in your Collection are going to be Integers, so for instance this will not compile:
Double d = 10d;
encodingQueue.add(d); <-- Compilation error
2) The reason why Integer is used instead of int is that you cannot store into collections primitive data types but you have to use objects; you can still write encodingQueue.add(10) thanks to the automatic boxing of ints inside Integers, but when you declare a typed collection (or, in general, a parameterized class) you have to use a class that extends Object as the parameter.
the <Integer> specifies the type of the data that the object is going to hold. it is Integer instead of int because the LinkedList is designed to hold an Object and not a primitive. so
Queue<Integer> q = new LinkedList<Integer>();
means that we are creating an Object of LinkedList that holds Integer type objects and we are refering it with a Queue reference variable.
what is the <> used with Integer for? And why is it also with the
LinkedList object and not in the parameters?
If you have a Parameterized Collection Queue<Integer> than a Raw type Queue
it ensures that none of the Objects other than Integer are added in the Collection.
This feature was introduced from Java 1.5
Why is the word Integer used and not int?.
Collection deals with Objects and not primitives.
Consider this example from Effective Java Item 23
// Now a raw collection type - don't do this!
/**
* My stamp collection. Contains only Stamp instances.
*/
private final Collection stamps = ... ;
If you accidentally put a coin into your stamp collection, the
erroneous insertion compiles and runs without error:
// Erroneous insertion of coin into stamp collection
stamps.add(new Coin( ... ));
You don’t get an error until you retrieve the coin from the stamp
collection:
// Now a raw iterator type - don't do this!
for (Iterator i = stamps.iterator(); i.hasNext(); ) {
Stamp s = (Stamp) i.next(); // Throws ClassCastException
... // Do something with the stamp
}
Example with Parameterized
// Parameterized collection type - typesafe
private final Collection<Stamp> stamps = ... ;
From this declaration the compiler knows that stamps should contain
only Stamp instances and guarantees this to be the case, assuming your
entire code base is compiled with a compiler from release 1.5 or
later and all the code compiles with- out emitting (or suppressing;
see Item 24) any warnings. When stamps is declared with a
parameterized type, the erroneous insertion generates a compile-time
error message that tells you exactly what is wrong:
Test.java:9: add(Stamp) in Collection<Stamp> cannot be applied to (Coin)
stamps.add(new Coin());
They are a type of generic (see #JTigger's answer) this means they can be a queue/list of ANY Java object including custom Java objects, this allows you to use the queue/list functions on anything inside of Java without reinventing the wheel.
Example:
Say we have the custom Object "planet":
public Class Planet {
private String name;
public Planet(String name) { this.name = name; }
public String getName() { return name; }
}
and we want to put a list of planets inside a queue. We could create said queue, and use the already built add() and remove() methods. If Queue was not a Generic class we would have to build our own add() and remove() functions. So using Generics we can list all the names of the planets in the solar system:
public static void main (String args[]) {
Queue<Planet> solarSystem = new LinkedList<Planet>();
solarSystem.add(new Planet("Mercury"));
solarSystem.add(new Planet("Venus"));
solarSystem.add(new Planet("Earth"));
solarSystem.add(new Planet("Mars"));
solarSystem.add(new Planet("Jupiter"));
solarSystem.add(new Planet("Saturn"));
solarSystem.add(new Planet("Uranus"));
solarSystem.add(new Planet("Neptune"));
solarSystem.add(new Planet("Pluto")); //For Nostalgia's sake
for (int i = 0; i < 9; i++) {
System.out.println(solarSystem.element().getName());
solarSystem.remove();
}
}

ArrayList of ArrayList of ints in Java?

I am working on writing a sudoku solver and I want the grid to be stored as an arraylist of arraylist of ints...each spot will have an arraylist of ints of all possible numbers (or the definite value).
ArrayList<ArrayList<int>> sudoku_board = new ArrayList <ArrayList<int>>();
Java is throwing me an error saying "dimensions expected after token" on the ints.
Generic type parameters require reference types, rather than primitive types. Use
List<ArrayList<Integer>> sudoku_board = new ArrayList <ArrayList<Integer>>();
Also when coding to an interface use the interface as the reference type, in this case List. Everything that appears within the generics should remain as the implementation type due to the non co-variance of generics.
From #assylias comment, a more generic type of list is
List<List<Integer>> list = new ArrayList<List<Integer>>();
This will allow for List implementations types other than ArrayList to be added should refactoring be necessary later.
Use Integer wrapper class instead primitive.
ArrayList wont allow primitive as type argument.
List<ArrayList<Integer>> list= new ArrayList <ArrayList<Integer>>();
Arraylist is used to store objects not primitives, so change the signature accordingly.

Typecast a ArrayList.toArray() in Java to normal array

I'm having some trouble to do the following:
int[] tmpIntList = (int[])MyArrayList.toArray(someValue);
MyArrayList contains only numbers. I get a typecast error since ArrayList only returns Object[] but why isnt it possible to turn it into a int[] ?
An ArrayList can't contain int values, as it's backed by an Object[] (even when appropriately generic).
The closest you could come would be to have an Integer[] - which can't be cast to an int[]. You have to convert each element separately. I believe there are libraries which implement these conversions for all the primitive types.
Basically the problem is that Java generics don't support primitive types.
ArrayUtils.toPrimitive(..) will do the conversion between Integer[] and int[], if you really need it. (apache commons-lang)
So:
int[] tmpIntList = ArrayUtils.toPrimitive(MyArrayList.toArray(someValue));
Rather then including apache-commons for only this single method call, you can use
Integer[] .
#Bozho , thanks mate for this suggestion.

Categories