incompatible types: inference variable T has incompatible bounds [duplicate] - java

This question already has answers here:
How to create ArrayList (ArrayList<Integer>) from array (int[]) in Java
(5 answers)
Using Arrays.asList with int array
(2 answers)
Closed 8 years ago.
I have the following piece of code
public int solution(int X, int[] A) {
List<Integer> list = Arrays.asList(A);
For some reason it's throwing the following compilation error
Solution.java:11: error: incompatible types: inference variable T has
incompatible bounds
List list = Arrays.asList(A);
^
equality constraints: Integer
lower bounds: int[] where T is a type-variable:
T extends Object declared in method asList(T...)
I assume this a Java 8 feature, but I'm not sure how to resolve the error

Arrays.asList is expecting a variable number of Object. int is not an Object, but int[] is, thus Arrays.asList(A) will create a List<int[]> with just one element.
You can use IntStream.of(A).boxed().collect(Collectors.toList());

In Java 8 you can do
List<Integer> list = IntStream.of(a).boxed().collect(Collectors.toList());

There is no shortcut for converting from int[] to List as Arrays.asList does not deal with boxing and will just create a List which is not what you want. You have to make a utility method.
int[] ints = {1, 2, 3};
List<Integer> intList = new ArrayList<Integer>();
for (int index = 0; index < ints.length; index++)
{
intList.add(ints[index]);
}

Related

java Failed to convert int array to Set using Collectors.toSet() [duplicate]

This question already has answers here:
Java stream - map and store array of int into Set
(3 answers)
How do I convert a Java 8 IntStream to a List?
(5 answers)
Arrays.asList() not working as it should?
(12 answers)
Closed 2 days ago.
i can't understand basic thing here i have :
int[] arr = {2,5,2,4,6,6,1,5,4};
Set<Integer> orederSet = new HashSet<Integer>(Arrays.stream(arr).collect(Collectors.toSet()));
side note :
also this not working :
Set<Integer> orederSet = new HashSet<Integer>(Arrays.asList(arr));
which gives me compile error :
java: method collect in interface java.util.stream.IntStream cannot be applied to given types;
required: java.util.function.Supplier<R>,java.util.function.ObjIntConsumer<R>,java.util.function.BiConsumer<R,R>
found: java.util.stream.Collector<java.lang.Object,capture#1 of ?,java.util.Set<java.lang.Object>>
reason: cannot infer type-variable(s) R
(actual and formal argument lists differ in length)
I dont understand what is wrong in my code ..
Your arr is an int[]. That means you're calling Arrays#stream(int[]), which returns an IntStream. But none of the primitive stream interfaces1 have a #collect(Collector) method. You have to convert the IntStream into a Stream<Integer>. The easiest way to do that is with the IntStream#boxed() method.
int[] arr = {2, 5, 2, 4, 6, 6, 1, 5, 4};
Set<Integer> set =
Arrays.stream(arr) // IntStream
.boxed() // Stream<Integer>
.collect(Collectors.toSet()); // Set<Integer>
As for why the following doesn't work:
Set<Integer> set = new HashSet<>(Arrays.asList(arr));
That's due to Arrays.asList(arr) returning a List<int[]> rather than a List<Integer>.
Neither primitives nor arrays work especially well with generics. Arrays of primitives are worse. A primitive can at least be auto-boxed to the reference type (and vice versa, i.e., unboxed) when appropriate. But primitive arrays have no such special treatment.
1. The primitive stream interfaces include IntStream, LongStream, and DoubleStream.
Try to convert IntStream:
Set<Integer> orderSet = Arrays.stream(arr).boxed().collect(Collectors.toSet());

How to convert ArrayList<Integer> into the int[] without using the for loop in java [duplicate]

This question already has answers here:
How to convert an ArrayList containing Integers to primitive int array?
(19 answers)
Closed 5 months ago.
I am using the following way but I got an error
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(5);
int[] arr = list.toArray();
}
The error I got is
java: incompatible types: java.lang.Object[] cannot be converted to int[]
You should be able to use another option of toArray method which takes empty array as argument.
Integer[] arr = new Integer[list.size()];
list.toArray(arr);
Integer class support all operations available for int data type
toArray() method returns an array of type Object(Object[]). We need to
typecast it to Integer before using as Integer objects. If we do not
typecast, we get compilation error.
This would work fine
Object[] objects = list.toArray();
For getting directly int array, you can use streams() method of list and mapToInt() to convert ArrayList to array of primitive data type int
int[] arr = list.stream().mapToInt(i -> i).toArray();

(Java) Using lambda as comparator in Arrays.sort [duplicate]

This question already has answers here:
Java - Sort one array based on values of another array?
(12 answers)
In Java how do you sort one list based on another?
(23 answers)
Java: Sorting an array based on another array with indexOf method
(3 answers)
Closed 3 years ago.
I am trying to write a function that takes two parameters, int[] arr1 and int[] arr2. Then, it should sort arr1 in the order given in arr2. For example, if arr1 is [5,7,9,10,7,5] and arr2 is [7,9,10,5], the function should return [7,7,9,10,5,5], sorting arr1 in the order elements in arr2 are indexed.
I wrote my code as below, but I keep on getting an error at Arrays.sort. I think I am using lambda incorrectly. Can you specify what I am doing wrong?
public int[] relativeSortArray(int[] arr1, int[] arr2) {
Map<Integer, Integer> elemToInd = new HashMap<Integer, Integer>();
for (int i = 0; i < arr2.length; i++) {
elemToInd.put(arr2[i], i);
}
Arrays.sort(arr1, (int n1, int n2) -> elemToInd.get(n1) - elemToInd.get(n2));
return arr1;
}
You can change the type of arr1 (and of course return type), so that types conform (to Integer[]) and write simply:
Arrays.sort(arr1, Comparator.comparing(elemToInd::get));
But what you're doing is quite confusing. You cannot use generics with primitives, just reach to Arrays clas for helper methods. On the other hand for collections you can invoke sort method on them.
package java.util;
public static <T> void sort(T[] a, Comparator<? super T> c)
you can see when you use this method, Comparator type must super T ,so type of arr must be using Integer

ArrayList's toArray() Method not Working Properly

When looking through ArrayList's methods, I saw a method called toArray(). I tried out this method using the following code:
ArrayList<Integer> a = new ArrayList<>();
// Assigning random elements to the ArrayList
int[] b = a.toArray();
However, this showed the following exception in the compiler:
Incompatible types.
Required: int[]
Found: java.lang.Object[]
The next thing I tried next is down-casting it to int[]
ArrayList<Integer> a = new ArrayList<>();
// Assigning random elements to the ArrayList
int[] b = (int[]) a.toArray();
This showed another error:
Cannot cast java.lang.Object[] to int[]
The last thing I tried is making it an Integer[] instead, and down-casting it to Integer[]
ArrayList<Integer> a = new ArrayList<>();
// Assigning random elements to the ArrayList
Integer[] b = (Integer[]) a.toArray();
This one compiled, but as soon as I ran it it produced ClassCastException. How do I use this toArray() method without errors?
List can only hold reference types (like Integer). Integer is a wrapper type. To convert a List<Integer> to an int[] there is an option using a Stream to map the Integer values to int and then collect to an int[]. Like,
int[] b = a.stream().mapToInt(Integer::intValue).toArray();
System.out.println(Arrays.toString(b));
It's all written in the javadoc:
Integer[] b = a.toArray(new Integer[0]);
Extending the answer of #Matthieu, It seems you need to pass new Integer[]. Attaching an example link given in geeksforgeeks.
Integer[] arr = new Integer[a.size()];
arr = a.toArray(arr);

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