convert double to int in ArryList

• August 5th, 2013, 08:18 AM
vector_ever
convert double to int in ArryList
Hello,

assume that i have the flowing arrayList:

Code :

```ArrayList arr = new arrayList(); arr.add("hi"); arr.add(2.5); arr.add("x"); arr.add(2.9); arr.add(1.0);```

now i want to convert every double value in arr to integer, how to do that (just the double and ignore another types)
• August 5th, 2013, 08:26 AM
KevinWorkman
Re: convert double to int in ArryList
This thread has been cross posted here:

Java Programming Forums Cross Posting Rules

The Problems With Cross Posting

• August 5th, 2013, 09:41 AM
vector_ever
Re: convert double to int in ArryList
Code :

```public static void main(String[] args) { ArrayList arr = new ArrayList(); arr.add("hi"); arr.add(2.5); arr.add("x"); arr.add(2.9); arr.add(1.0);   for(int i = 0; i < arr.size(); i++){ if (arr.get(i) instanceof Double ){ (int)arr.get(i); //false, but how to do it correctly } } } }```
• August 5th, 2013, 02:34 PM
jps
Re: convert double to int in ArryList
"how to do it correctly" does not explain very much about the problem you face.
Is there an error?
Is the array just left unchanged, where you expected to see a change?

The line of code (int)arr.get(i); has no side effect, did you expect this to modify a value in the array?
• August 5th, 2013, 11:01 PM
Junky
Re: convert double to int in ArryList
Simple answer is DO NOT insert different types into the same List.
• August 6th, 2013, 06:43 AM
vector_ever
Re: convert double to int in ArryList
Quote:

Simple answer is DO NOT insert different types into the same List
Some times you don't have any another choice, any way the solution to do it

Code :

```public static void main(String[] args) { ArrayList arr = new ArrayList(); arr.add("hi"); arr.add(2.5); arr.add("x"); arr.add(2.9); arr.add(1.0);   for(int i = 0; i < arr.size(); i++){ if (arr.get(i) instanceof Double ){ int n = ((Double) arr.get(i)).intValue(); arr.set(i, n); } System.out.println(arr.get(i)); }   }```
• August 6th, 2013, 10:10 AM
llowe29
Re: convert double to int in ArryList
• August 6th, 2013, 10:14 AM
KevinWorkman
Re: convert double to int in ArryList
Quote:

Originally Posted by llowe29

He was posting the solution to his own problem. The user who posted the solution *is* the OP. This is actually pretty okay.
• August 6th, 2013, 10:45 AM
GregBrannon
Re: convert double to int in ArryList
Quote:

Originally Posted by llowe29