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

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<>();

Related

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

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();

Remove every element in ArrayList [duplicate]

This question already has answers here:
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
(31 answers)
Closed 5 years ago.
I'm currently learning Java, I'm just curious about the code that I wrote a minute ago, it works, but I want to know if there is a better alternative (that isn't "use the clear method").
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add("A");
al.add("B");
al.add(5);
System.out.println(al.size());
Iterator i = al.iterator();
while (i.hasNext()) {
Object next = i.next();
System.out.println("Removing " + next.toString() + "...");
al.remove(next);
i = al.iterator();
}
System.out.println(al.size());
}
Especially, because I don't really know what can be in a specific position in an ArrayList (they contains objects of every kind), I used a generic "Object next" variable. I don't know if it is acceptable.
I know that there are methods to clear an ArrayList, I just wanted to try to understand how ArrayLists works, thank you.
You don't need to fetch each element before you remove it. You can simply remove elements by it's index:
ArrayList al = new ArrayList();
// ... add elements skipped...
// now clear it
int size = al.size();
for (int index = size-1; index >= 0; index--) {
al.remove(index);
}
but I want to know if there is a better alternative
Yes.
because I don't really know what can be in a specific position in an
ArrayList (they contains objects of every kind.
Make List<T> generic : it will allow you to add only some specific type of Object.
Replaced ArrayList al = new ArrayList(); by
List<String> al = new ArrayList<>();

Enhanced for loop not working for assigning values to an array (Java) [duplicate]

This question already has answers here:
Why does the foreach statement not change the element value?
(6 answers)
Closed 5 years ago.
I don't understand why I cannot assign values to the elements of an array using the enhanced for loop.
For example, using for loop like that
int[] array = new int[5];
for(int i = 0; i < 5; i++)
array[i] = 10;
produces what I want.
But why does that not work with "for each":
for(int element : array)
element = 10;
Is there any specific reason why that is the case or am I doing something wrong?
In the enhanced for loop element is a local variable containing a reference (or value in case of primitives) to the current element of the array or Iterable you are iterating over.
Assigning to it doesn't affect the array / Iterable.
It's equivalent to :
int[] array = new int[5];
for(int i = 0; i < 5; i++) {
int element = array[i];
element = 10;
}
Which also won't modify the array.
If you need to modify the array, use should use a regular for loop.
The enhanced for loop you use :
for(int element : array)
element = 10;
In java we have references referencing an object. At a time one reference can reference to only one object. If it is made to reference another object then it losses the reference to the previous one.
When you use = then you make element to reference another value i.e 10.
Here element is of type int, which is primitive type. Even if
it was an Integer then also Integer being immutable you would
have not been able to make any modifications in the object as
modifications always would have resulted in a separate object.
If it would have been the case as below for some Custom class say Student.java
For some List<Student> students.
for(Student std : students){
std.setName("eureka");
}
Now iterating the list and printing the name of each student would have
resulted in printing eureka for each student. But note that even in this case use of = would have again produced same result as you are getting now (as again you would have referenced the variable to different object, it would no longer reference to the original object of the list).

Why I convert ArrayList to Interger[] is wrong? [duplicate]

This question already has answers here:
Convert ArrayList<String> to String[] array [duplicate]
(6 answers)
Closed 7 years ago.
private ArrayList<Integer> list;
...
...
...
for (int i=0; i < list.size(); i++) {
Log.e("downloadTask","resource ID is " + list.get(i));
}
Integer[] resourceId = resourceId= (Integer[])list.toArray();
before for() statement, list had already been initialized. It has three elements;
The Log message is right, but when run
Integer[] resourceId = (Integer[]) list.toArray();
it will throw Exceptions. I don't know how to solve this problem.
list.toArray() returns an array of objects (Object[]), which can not be cast to an integer array (because Object[] can contain anything, like String, Boolean, SpiderMan, not only Integer).
Try:
list.toArray(new Integer[list.size()]); //will fill and return passed array
//with all elements from list
In the future, please provide the exact exceptions being thrown (and include the stack trace) so it's easier for people to spot the problem.

Trouble with generic arrays in Java [duplicate]

This question already has answers here:
How to create a generic array? [duplicate]
(4 answers)
How to create a generic array in Java?
(32 answers)
Closed 8 years ago.
I am working on a problem and I was provided with the following method header:
T[] getAll(T[] elements)
I am not allowed to modify it.
The purpose of the method is to fill the elements array with elements from a member list. Before this is done however we need to check if the array's capacity is large enough for all the elements to fit. If it is not we have to create a new array with an appropriate capacity.
How do I create an array when I do not know which datatype the elements are? As far as I know it's not possible to create generic arrays.
#Override
public T[] getAll(T[] elements)
{
// TODO create new array if needed
for(int i = 0; i < size(); i++)
{
elements[i] = list.element();
list.move();
}
return elements;
}

Categories

Resources