1 Replies - 9373 Views - Last Post: 13 March 2014 - 10:54 AM Rate Topic: -----

#1 crazycommander   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 12-March 14

Generic class ArrayList min/max values

Posted 13 March 2014 - 09:58 AM

The assignement is to write a Generic class<T> that has an add method to add the values of Number type to an ArrayList. Then write a largest and smallest method to determine the largest and smallest numbers in the ArrayList.

The problem i am having is that when i run the program it only compares the first two numbers of the ArrayList and does not factor in the rest.

import java.util.ArrayList;

public class JEB_003_001<T extends Number> {
	ArrayList<T> al = new ArrayList<T>();
public void add(T number){
	al.add(number);
}
public T largest(){
	T large = al.get(0);
	for (int i = 0; i < al.size(); i++){
		if(al.get(i).toString().compareTo(large.toString()) > 0)
			large = al.get(i);
	}
	return large;
}
public T smallest(){
	T small = al.get(0);
	for(int i=0; i < al.size(); i++){
		if(al.get(i).toString().compareTo(small.toString()) < 0)
			small = al.get(i);
	}
	return small;
}
public void display(){
	System.out.println(al);
}
}


and my driver is

public class JEB_003_001_002 {
	
	public static void main(String args[]){ 
		JEB_003_001<Number> list = new JEB_003_001<Number>();
		list.add(7);
		list.add(-9);
		list.add(23);
		list.add(18);
		list.add(12);
				
		System.out.println("The numbers from the list are: ");
		list.display();
			
		Number largest = list.largest();
		System.out.println();
		System.out.println("The largest number from the list is: " + largest);
		
		Number smallest = list.smallest();
		System.out.println();
		System.out.println("The smallest number in the list is: " + smallest);
	}

}


Is This A Good Question/Topic? 0
  • +

Replies To: Generic class ArrayList min/max values

#2 g00se   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3744
  • View blog
  • Posts: 17,121
  • Joined: 20-September 08

Re: Generic class ArrayList min/max values

Posted 13 March 2014 - 10:54 AM

http://docs.oracle.c...til.Collection)

I would mark you up for using that, not down. There's min as well
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1