Let us imagine that we are having a arraylist in java which contains both intergers and strings value. I would like to loop through the entire arraylist(only taking the integers,ignore string) to find the largest number on the list???i need a program for this task????help me please
Asked
Active
Viewed 2,430 times
-4
-
5Could you show us what you've tried? – PakkuDon Apr 02 '14 at 11:30
-
possible duplicate http://stackoverflow.com/questions/1484347/java-max-min-value-in-an-array – Apr 02 '14 at 11:30
-
Use a for-loop with an `instanceof` check. – Marko Topolnik Apr 02 '14 at 11:30
-
Questions asking for code must demonstrate a minimal understanding of the problem being solved. – Jonesopolis Apr 02 '14 at 12:39
5 Answers
2
Asuming an Object ArrayList, something like this should work:
int biggest = Integer.MIN_VALUE;
for (Object item : list) {
if(item instanceof Integer && (Integer) item > biggest)
biggest = item;
}

robertoia
- 2,301
- 23
- 29
0
- Don't keep different data types in a list. Use generics extensively.
- you can use instanceOf (ArrayList keeps Integers and Strings) to check type and put the int's seperately and get the largest value.

TheLostMind
- 35,966
- 12
- 68
- 104
0
private int getLargestNumber(ArrayList<Objects> list){
int max = Integer.MIN_VALUE;
for(int i = 0; i < list.size(); i++){
Object obj = list.get(i);
if(obj instanceof Integer && max < (Integer) obj)
max = (Integer)obj;
}
return max;
}

Jilberta
- 2,836
- 5
- 30
- 44
0
When you pass a ArayList object to the below function it will return the bigest Integer from the list ..
public static Integer getLargerInteger(ArrayList list){
ArrayList temp=new ArrayList<Integer>();
for (Object object : list) {
if(object instanceof Integer){
temp.add(object);
}
}
return Collections.max(temp);
}

loknath
- 1,362
- 16
- 25
0
You can try the below approach using Comparator Interface rather then looping through all the elements.
List arr = new ArrayList();
arr.add(2);
arr.add(5);
arr.add(10);
arr.add(20);
arr.add("s1");
arr.add("s2");
arr.add("s3");
Collections.sort(arr, new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
if(o1 instanceof Integer && o2 instanceof Integer){
Integer ob1 = (Integer) o1;
Integer ob2 = (Integer) o2;
return ob2.compareTo(ob1);
}else{
return -1;
}
}
});
System.out.println(arr.get(0));

user3467480
- 93
- 3