adding array to linkedList [duplicate] - java

This question already has answers here:
What causes javac to issue the "uses unchecked or unsafe operations" warning
(12 answers)
Closed 3 years ago.
im getting uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details. error when adding array to linkedlist
Here is my work
LinkedList main_list = new LinkedList();
int arr = new int[2]
arr[0] = 0;
arr[1] = 1;
main_list.add(arr);

The compiler warning messages convey that the operation you are trying to is unsafe!
This comes up in Java 5 and later if you're using collections without type specifiers. (See generics )
Here you are creating a LinkedList() without specifying its type. It means that the compiler can't check that you're using the collection in a type-safe way, using generics.
You should create it like below by specifying its type.
LinkedList<int[]> myList = new LinkedList<>();

You can just have a list of Interger arrays:
LinkedList <int[]> main_list = new LinkedList <>();
int[] arr = {0,1};
int[] arr2 = {2,3};
main_list.add(arr);
main_list.add(arr2);
with this structure all of your Integer arrays will keep their initial boundaries and the result will not be stored in a long flat list. You can access them independently for later use.

You can add it directly by using Arrays.asList(arr). You can directly convert Array into list by using asList() function. Use the following code:
LinkedList main_list = new LinkedList(Arrays.asList(arr));

First convert Array into list and then add it into list. If your Arrays only contain Integers then you create Integer List and array of Integers. Like
Integer[] arr = new Integer[2];
arr[0] = 0;
arr[1] = 1;
List<Integer> main_list = new LinkedList<>();
main_list.add(Arrays.asList(arr));
It will work. Or if you want to save array at every index of lined list then you have to create list of arrays of
Integers. Like
List<Integer[]> main_list = new LinkedList<>();
Integer[] arr = new Integer[2];
arr[0] = 0;
arr[1] = 1;
main_list.add(arr);

Related

Temporary ArrayList Replacement [duplicate]

This question already has answers here:
Why does one arraylist change when a copy of it is modified
(6 answers)
Closed 3 years ago.
I'm setting a temporary ArrayList equal to a pre-established ArrayList. Changes to the temporary ArrayList seem to also transfer over to the pre-established one. Why does this occur and how can I keep the pre-established ArrayList unchanged?
I know that this phenomenon does not occur in situations that involve ints.
ArrayList<Integer> array = new ArrayList<>();
for (int i = 0; i < 3; i++){
array.add(i);
}
ArrayList<Integer> tempArr = array;
tempArr.remove(0);
I expect array to be [0,1,2], but I get [1,2]. I would like the output to be array = [0,1,2] and tempArr = [1,2].
You just copied the reference of the list to the new variable. That means you have 2 references array and tempArr that are pointing to the same object. You could create a new ArrayList from the old one:
ArrayList<Integer> tempArr = new ArrayList<>(array);
Variables array and tempArr booth point to same instance of ArrayList<Integer> object, hence modifying one will make changes to other.
What you need is to create new instance and then transfer all elements to it:
ArrayList<Integer> array = new ArrayList<>();
for (int i = 0; i < 3; i++){
array.add(i);
}
ArrayList<Integer> tempArr = new Arraylist<>();
tempArr.addAll(array);
tempArr.remove(0);
This code can also be simplified since Arraylist<> is offering you constructor that will add elements from another collection:
ArrayList<Integer> tempArr = new Arraylist<>(array);
tempArr.remove(0);

Defining an array of List of integers in Java

I have an array. For each element of the array, I want to store multiple integers. I know that in C I can make an array of integer pointers, and use that pointer to make a list.
In Java, I can make an array of object 'A', where A has a list of integers. But why can't I do something like this
List<Integer>[] arr = new ArrayList<Integer>[]();
I get:
Type mismatch: cannot convert from ArrayList to List[]
You typically want to avoid mixing collections and arrays together for this very reason; an array is covariant (that is, Integer[] is-an Object[]), but collections (and generics in general) are invariant (that is, a List<Integer> is not a List<Object>).
You can definitely create a list of lists instead, which will ensure type safety and get you around the issue of creating a generic array:
List<List<Integer>> intNestedList = new ArrayList<>();
As stated in Java's own documentation, you cannot create an array of generics.
If you want to create an array which can hold up to ten List<Integer> you must declare the array that way.
List<Integer>[] arr = new ArrayList[10];
following assignment is valid
List<Integer> intList = new ArrayList<>();
arr[0] = intList;
whereas following will fail with an compilation error
List<String> stringList = new ArrayList<>();
arr[0] = stringList;
the compilation fails with
incompatible types: java.util.List<java.lang.String>
cannot be converted to java.util.List<java.lang.Integer>
An ArrayList is a List, but an ArrayList is not a List[]
If you want an Array of Lists that hold integers, I would suggest:
List<Integer>[] xyz; // still writing code will update in a sec
It turns out you can't create arrays of parameterized types, according to the oracle docs.
Unless you know for sure you want a finite array, I suggest you do something like List<List<Integer>> arr = new ArrayList<List<Integer>>();
If you really want an array of Lists then you'll want to see this Java question about ArrayList<Integer>[] x
Creating an array of List is no different than creating an array of any other object. You can do any of the following:
List[] listsArray = new List[3];
listsArray[0] = new ArrayList();
listsArray[1] = new LinkedList();
listsArray[2] = new ArrayList();
Or:
List[] listsArray = new List[]{new ArrayList(), new LinkedList(), new ArrayList()};
Note that you are limited in what you can do with generics on arrays.
Not a very nice solution but you might try it with a cast. Something like this:
List<Integer>[] arr = (List<Integer>[]) new List[SIZE_OF_YOUR_ARRAY];
You will probably get a warning but it should still work.
As i found, you need an array of arrays.
you can do this, to make your inner arrays:
Integer[] array1 = new Integer[];
Integer[] array2 = new Integer[];
and then put them in another array like this:
Integer[][] arrays = new Integer[][] { array1, array2 };
or
Integer[][] arrays = { array1, array2 };
maybe it's better to do it like this:
List<List<Integer>> listOfLists = Lists.newArrayList();
listOfLists.add(Lists.newArrayList("123","456","789"));
after all I recommend you to read this:
How to make an array of arrays in Java
Graph Implementation using Adjacency List depicts the usage of an Array of List.
public class Graph {
int vertex;
LinkedList<Integer> list[];
public Graph(int vertex) {
this.vertex = vertex;
list = new LinkedList[vertex];
for (int i = 0; i <vertex ; i++) {
list[i] = new LinkedList<>();
}
}
}
As you can observe that the constructor of class Graph, is used to define the Array of List.
in the same constructor, Array Of List is initialized too.
Hope It would be Helpful to resolve your problem and requirement !.

Can we have an Array of a collection?

I was trying create an array of a collection as follows.
ArrayList<Integer> ar[]=new ArrayList<Integer>[50];
but it gives me an error -> generic array creation
can anybody explain me why is it?
You can't create arrays of generic types. Use collection of collections instead:
ArrayList<ArrayList<Integer>> = new ArrayList<ArrayList<Integer>>();
Why can't we create an array of generic type? Array stores they exact type internally, but due to the type erasure at runtime there will be no generic type. So, to prevent you from been fooled by this (see example below) you can't create an array of generic type:
//THIS CODE WILL NOT COMPILE
ArrayList<Integer>[] arr = new ArrayList<Integer>[5];
Object[] obj = arr;
obj[0] = new ArrayList<Long>(); //no one is safe
ArrayList is internally a 1D array itself. what you need 2D array so you can create
ArrayList<Integer[]> ar=new ArrayList<Integer[]>();
or
ArrayList<ArrayList<Integer>> = new ArrayList<ArrayList<Integer>>();
The answer to you question can be found in the Java Language Specification. You are trying to create an array using Array Creation Expression. It says the following: "It is a compile-time error if the ClassOrInterfaceType does not denote a reifiable type". Because arrays in Java are created at runtime, their type information should be completely available at runtime. In other words array element type should be a reifiable type. Generics in Java are implemented using type erasure (i.e. only subset of generics compile-time type information is available at runtime) hence they are not reifiable by definition and therefore you cannot create arrays of generic types.
Actually you can have an Array of Collection, it just is not allowed that the Collection has a specific type.
You can do something like
ArrayList<?>[] ar = new ArrayList<?>[50];
// or ArrayList[] ar = new ArrayList[50];
ar[0] = new ArrayList<Integer>();
but you will not have the benefits of Generics - there is no type information for the content of the Collection, you will need to cast when reading from it
Integer i = (Integer) ar[0].get(0);
You could do something like this
ArrayList<Integer> ar[]= new ArrayList[50];
ArrayList<Integer> intArr = new ArrayList<Integer>();
ArrayList<Long> longArr = new ArrayList<Long>();
ar[0]=intArr;
ar[1]= longArr; // compile error Type mismatch: cannot convert from ArrayList<Long> to ArrayList<Integer>
You can have an array "technically" of type ArrayList but its a bit nit picky. Create it as an ArrayList<ArrayList<Integer>> list = ArrayList<ArrayList<Integer>(); and convert it using toArray(ArrayList<Integer>[list.size()]);.
Example:
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
list.add(new ArrayList<Integer>());
list.add(new ArrayList<Integer>());
list.add(new ArrayList<Integer>());
int count = 1;
for(ArrayList<Integer> AList: list) {
for(int i = 0; i < 4; i++)
AList.add(count++);
}
ArrayList<Integer>[] check = list.toArray(new ArrayList[list.size()]);
for(ArrayList<Integer> AL : check) {
for(Integer i:AL) {
System.out.print(i + " ");
}
System.out.println();
}
Output:
1 2 3 4
5 6 7 8
9 10 11 12
Works and is an ArrayList array

ArrayList of Array of Strings

What is the difference between the two data structures defined below?
The second one is an ArrayList, whose elements have type 'String'. But what is the first data structure?
The initializations would also be different. Can anyone give an example here?
ArrayList<String>[] temp1;
ArrayList<String> temp2;
ArrayList<String>[] temp1;: This is an Array of ArrayList's that are containing Strings
ArrayList<String> temp2;: This is an ArrayList containing Strings
If you want an ArrayList of Arrays of Strings, you would have to do a ArrayList<String[]> temp3;. Note the position of the different brackets.
To initialize:
// create an array with 10 uninitialized ArrayList<String>
ArrayList<String>[] temp1 = new ArrayList[10];
// create empty lists that can be filled
for (int i=0; i<temp1.length; i++)
temp1[i] = new ArrayList<String>();
// create an empty list of Strings
ArrayList<String> temp2 = new ArrayList<String>();
// create an empty list of String arrays
ArrayList<String[]> temp3 = new ArrayList<String[]>();
I provide some example to differentiate the Array of ArrayList and ArrayList of String
public class ArrayOfArrayList {
public static void main(String[] args) {
// Declare the Array of ArrayList
List<String>[] arrayOfList = new ArrayList[2];
// Declare the Object of ArrayList
for(int i = 0; i < arrayOfList.length; i++) {
arrayOfList[i] = new ArrayList<>();
arrayOfList[i].add("" + (i + 1));
arrayOfList[i].add("" + (i + 2));
}
// Print out the result
for(List<String> list : arrayOfList) {
for(String str : list) {
System.out.println(str);
}
}
// Declare the Object of ArrayList
List<String> arrayList = new ArrayList<>();
arrayList.add("1");
arrayList.add("2");
// Print out the result
for(String str : arrayList) {
System.out.println(str);
}
}
}
The first data structure is an array of ArrayLists containing string objects
The first is an array of classes of the type ArrayList<String>. The second is simply an ArrayList<String> (ArrayList of Strings.)
In terms of initialisations:
ArrayList<String>[] lists = (ArrayList<String>[])new ArrayList[10];
ArrayList<String> temp2 = new ArrayList<String>();
The first initialisation has to specify a size for the array (note this is not a size for the ArrayList) and this is where the 10 comes from in my example. It can be any size you choose of course, 10 is just an arbitrary example. It will also generate a warning, but, if you really want an array of ArrayList<String> this is AFAIK the only way for now (the reason stems from the fact generics in Java aren't reified, but array types are.)
The second one is an ArrayList, whose elements have type 'String'. But what is the first data structure?
On the surface, it would appear to be an array of lists (containing strings). However arrays and generics don't play very well together. From the article:
Another consequence of the fact that arrays are covariant but generics are not is that you cannot instantiate an array of a generic type (new List<String>[3] is illegal), unless the type argument is an unbounded wildcard (new List<?>[3] is legal). Let's see what would happen if you were allowed to declare arrays of generic types:
List<String>[] lsa = new List<String>[10]; // illegal
Object[] oa = lsa; // OK because List<String> is a subtype of Object
List<Integer> li = new ArrayList<Integer>();
li.add(new Integer(3));
oa[0] = li;
String s = lsa[0].get(0);
The last line will throw a ClassCastException, because you've managed to cram a List<Integer> into what should have been a List<String>. Because array covariance would have allowed you to subvert the type safety of generics, instantiating arrays of generic types (except for types whose type arguments are unbounded wildcards, like List<?>) has been disallowed.
Yes, first is the Array of ArrayList and will have strings value in it.
second statement is only array list of Strings value.

Can I convert array of integer to List<int> or List<Integer> by Arrays.asList(array)? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Arrays.asList() not working as it should?
How to convert int[] into List<Integer> in Java?
Or must I refactor int[] to Integer[] ?
You can't have List<int>
Arrays.asList(array); will return you List with type T of (passed array)
You can have something like
Integer[] a = new Integer[]{1,2,3};
List<Integer> lst = Arrays.asList(a);
You can do this way
Integer[] a ={1,2,4};
List<Integer> intList = Arrays.asList(a);
System.out.println(intList);
Arrays.asList(array) returns a List-type view on the array. So you can use the List interface to access the values of the wrapped array of java primitives.
Now what happens if we pass an array of java Objects and an array of java primitive values? The method takes a variable number of java objects. A java primitive is not an object. Java could use autoboxing to create wrapper instances, but in this case, it will take the array itself as an java object. So we end up like this:
List<Integer> list1 = Arrays.asList(new Integer[]{1,2,3}));
List<int[]> list2 = Arrays.asList(new int[]{1,2,3}));
The first collection holds the integer values, the second one the int[] array. No autoboxing here.
So if you want to convert an array of java primitives to a List, you can't use Arrays.asList, because it will simply return a List that contains just one item: the array.
If you have a array of Integers then you can use Arrays.asList() to get a List of Integers:
Integer[] inters = new Integer[5];
List<Integer> ints = Arrays.asList(inters);
EDIT :
From the comment below from develman, java 6 has support to return List<> object for same method
OLD ANSWER :
Arrays.asList(array) returns you a java.util.List object.

Categories

Resources