Getting an error in my code how to fix it? [duplicate] - java

This question already has answers here:
What is a raw type and why shouldn't we use it?
(16 answers)
Closed 4 years ago.
I have the following code:
public static void poistaKaikki32(LinkedList L1, Collection L2) {
LinkedList<Integer> temp = new LinkedList<>();
HashSet<Integer> L2Set = new HashSet<>(L2);
// first filter elements into temp
while (L1.size() > 0) { // n loops
int v = L1.removeFirst(); <--- getting error cannot convert object to int
if (!L2Set.contains(v)) {
temp.addLast(v);
}
}
// add filtered values back to L1
while (temp.size() > 0) {
L1.addLast(temp.removeFirst());
}
}
I keep getting an error on int v = L1.removeFirst();. How would i fix this, without using casts.

argument to method is of raw type thats why when you do a get operation on it you get an object type .to make this work either TYPECAST it while doing a get operation using
Integer v = (Integer)L1.removeFirst();
or change the method parameter type LinkedList L1 to LinkedList<Integer> L1
but best way to do it is second one change the parameter type

Please try
Integer v = (Integer)L1.removeFirst();

Related

Create Static Array from dynamic array with Generics [duplicate]

This question already has answers here:
why does List<String>.toArray() return Object[] and not String[]? how to work around this?
(5 answers)
Closed 3 years ago.
I want to create a static array from a dynamic array of whatever generic type the dynamic array was. I saw List#toArray() which returns Object[] and it doesn't use generics. Is it just safe to cast it to T[] or does the entire array have to be instantiated from the type of class using it?
I went on to try and create my own method in case java didn't provide one but, I got stuck with a compile errors
public static <T> T[] toArray(List<T> list)
{
T[] li = (T[]) Array.newInstance(T.class, list.size());
int index = 0;
for(T obj : list)
{
li[index++] = obj;
}
return li;
}
First of all, you don't need that method. You can use:
List<String> list = new ArrayList<>();
list.add("ff");
list.add("bb");
String[] array = list.toArray (new String[list.size ()]);
In order for your method to work, you have to pass the Class of the generic type parameter:
public static <T> T[] toArray(List<T> list, Class<T> clazz)
{
T[] li = (T[]) Array.newInstance(clazz, list.size());
int index = 0;
for(T obj : list)
{
li[index++] = obj;
}
return li;
}
Then you can call the method with:
String[] array = toArray(list, String.class);
The method proposed by Eran doesn't work if you have a generic element type, because you can't get a Class<List<T>>, say.
Instead, pass an IntFunction<T[]>:
public static <T> T[] toArray(List<? extends T> list, IntFunction<T[]> arraySupplier)
{
T[] li = arraySupplier.get(list.size());
int index = 0;
for(T obj : list)
{
li[index++] = obj;
}
return li;
}
Or, easier, use streams:
return list.stream().toArray(arraySupplier);
Then call like:
String[] array = toArray(list, String[]::new);
List<List<String>> listOfLists = ...
List<?>[] arrayOfLists = toArray(listOfLists, List<?>::new);
Notice that whilst this does support generic array elements, you can only create arrays with a reified element type, so your array type has to be List<?>[]; it still can't be List<String>[].
If your business requirement/Use Case requires an array to be no longer dynamic then you should first create a static array of size equal to your size of dynamic array.
ArrayList<Integer> al = [............] // assuming that ArrayList named al is having some data
int[] arr = new int[al.size()];
// from here you can use a for loop and initialize your static array
for(int i=0; i<arr.length;i++) {
arr[i] = (int) al.get(i); // Unboxing will also be done but still you can type cast to be on safe side
}
// Now you can de-reference the ArrayList object and call garbage collection which will wipe it out of the Heap Memory of your JVM.
al = null; // de-referencing the object by making the reference variable null
System.gc(); // GC happens periodically but to boost performance you can explicitly call it right away.
You can create a method accepting the list of objects and can handle all sorts of arrays using instanceof operator.

Java compile error: List<Integer> cannot be converted to ArrayList<Integer> [duplicate]

This question already has answers here:
List<Integer> cannot be converted to ArrayList<Integer>
(3 answers)
Closed 4 years ago.
The program is like:
public class Proj {
public List dsp(ArrayList<Integer> list) {
return list;
}
public static void main(String[] args) {
int[] nums = {4,3,2,7,8,2,3,1};
List<Integer> bl = new ArrayList<>();
for (int var : nums) {
bl.add(var);
}
Proj p = new Proj();
p.dsp(bl);
System.out.println(bl);
}
}
Error message:
incompatible types: List cannot be converted to ArrayList
at the line p.dsp(bl);
How to fix the error?
Not every List<Integer> is a ArrayList<Integer>. The dsp method accepts a ArrayList<Integer> so to make it work you'll pass a type ArrayList<Integer> or change your method to accept List<Integer>.
Also, make use of generics, I'd use List<Integer> for the return type instead of List.
You can‘t cast from parent to children, your dsp method should accept List in place of ArrayList

Why can ArrayList elements not be converted to ints? [duplicate]

This question already has answers here:
What is a raw type and why shouldn't we use it?
(16 answers)
Closed 7 years ago.
I know I have done this in the past. I have an ArrayList that has been populated with integers. I need to iterate over it and find the maximum value. However, when I iterate over an array with something like this:
for (int i = 0; i < list.size(); i++)
{
if (list.get(i) > max)
{
max = list.get(i);
}
}
I get an error that says java.lang.Object cannot be converted to int or that > is a bad operand type. I have never encountered this before, and I have used arraylists multiple times for this same purpose. What am I doing wrong here?
max is declared as an int but is not initialized.
Most likely you declared the ArrayList just like this:
ArrayList list = new ArrayList<>();
instead of :
ArrayList<Integer> list = new ArrayList<>();

Representing array of lists

This seems like basic question, but it has really confused me. I ma trying to represent the adjacency list of a graph. I have two questions :
public class Graph
{
private final int V;
private List<Integer>[] adj;
public Graph(int V)
{
this.V = V;
this.adj = (List<Integer>[]) new LinkedList[V]; // this works
}
}
Question 1: when I do the below, it gives an error saying
Array type expected; found: 'java.util.LinkedList<java.lang.Integer>'
this.adj = (List<Integer>[]) new LinkedList<Integer>()[V];
I am creating a List of Integer arrays, right ?
Question 2: when I do this, it again gives an error saying generic array creation:
this.adj = (List<Integer>[]) new LinkedList<Integer>[V];
What is the problem with the last two approaches ? i think the first one is more correct.
In (1), your expression is being parsed as
(new LinkedList<Integer>())[V]
which is attempting to index a freshly-created LinkedList, hence the error.
In (2), you are trying to make an array of generics. You can't do this. Instead, consider using some container type (like an ArrayList<List<Integer>>).
You are trying to create an array of list of integer. That means each index can have multiple count. So, you need to initialize each index.
public Graph(int v)
{
V = v;
adj = new List<int>[v];
for (int i = 0; i < v; ++i)
adj[i] = new List<int>();
}

How can I construct an array of a parameterized type? [duplicate]

This question already has answers here:
How to create a generic array in Java?
(32 answers)
Closed 8 years ago.
I will get right into the problem here.
This is the method that I have so far:
public T[] getAllValues() {
Serializable[] result = new Serializable[sets.size()];
for (int i = 0; i < sets.size(); i++) {
result[i] = sets.get(i).getValue();
}
return (T[]) result;
}
'T' is a parameterized type that extends Serializable.
'sets' is an ArrayList holding a type that stores both a String (key) and a T (value),
so getValue() returns a T.
In this method, I want to return all Ts in an array, so what I would actually like to do looks more like this:
public T[] getAllValues() {
T[] result = new T[sets.size()];
for (int i = 0; i < sets.size(); i++) {
result[i] = sets.get(i).getValue();
}
return result;
}
So the Serializable array, that is casted to a T array was just an idea as a work-around, but does not work unfortunately. But at the same time, I cannot use the second version, because
new T[int];
is obviously not possible to construct when the type is parameterized. Why is that?
And more importantly: How can I work around it?
Thank you in advance
EDIT: I solved the problem, this is what I came up with:
public T[] getAllValues(T[] typearray) {
for (int i = 0; (i < typearray.length) && (i < sets.size()); i++) {
typearray[i] = sets.get(i).getValue();
}
return typearray;
}
You should avoid using arrays in general and it won't work at all in this case.
Using List<T> (or Set<T>) instead of an array solves all your problems.
Aside comment:
I'm not sure what you are doing, but it seems that instead of having a sets that contains a list of pairs (String, T), you could have a Map<String, T>. You would not need your method getAllValue() since map.values() returns a Collections<T> of all T's.

Categories

Resources