[EduCoder] generic programming -- comparison

Generic is a high-level programming mechanism. It can abstract and encapsulate the same operation of different types of objects, so that it has wider code reusability. It is the reuse embodiment of implementing the same operation on different types of data. In programming, we often encounter the situation that different data types can implement the same operation.

1 this related task - defining generic classes

Complete the generic programming code on the right and pass the test.


Definition of generic type:

public class A< T>{
    private T t;
    public A(T t){this.t=t;}
    public T getT(){return t;}
    public void setT(T t){this.t=t;}
    public String toString(){return " "+t;}

The type parameter T is introduced into this class, which is written after the class name and enclosed in a pair of angle brackets. With this definition, you can use it in the following ways.

A i= new A<Integer>(new Integer(20));
A s= new A<String>("Hello");
A d= new A<Double>(3.0);
System.out.println(i+" "+s+" "+d);}

Output: 20 Hello 3.0

Note: in the definition of class A, it is not specified that the data member t must be a specific type. Instead, it is defined as generic data T. it is specified only when it is used, that is, in the test class. The data type is defined.
In the test class, when defining the objects, i, s and d of class A, replace the type parameter T with Integer, indicating that the positions of all T in the class are Integer; Replace the type parameter T with String, indicating that the positions of all T in the class are String, which can not only enable various types to reuse the same piece of program code, but also avoid the errors caused by artificial forced type conversion.

be careful

Basic data types are not allowed when instantiating generic classes. For example, a < double > is wrong and must be written as a < double >.

Clearance tips

Sometimes the parameter type needs to be qualified. For example, the classes required to be brought in must have the function of comparing sizes, that is, these classes must implement the Comparable interface. The format of this restriction is:

public class A < T extends Comparable>{

< T extends Comparable > means that t is limited to a subclass of Comparable. Note that although Comparable is an interface, the extends keyword is used here instead of the implements keyword.

The compare() method needs to be implemented in this level to return the larger of the two objects. The following compareto() method is used, where obj1 and obj2 are two objects of the same type.
obj1.compareTo(obj2) returns values greater than 0, less than 0 and equal to 0, representing that object obj1 is greater than, less than and equal to object obj2.

Programming requirements

Complete the generic programming code on the right, define generic classes, compare the two objects, and output the largest. The input data may be an integer, a floating-point number, or a string.

String size, in alphabetical order, such as C > a.

Start your mission. I wish you success!

Answer code:

package step1;

public class A< T extends Comparable >{
 private T t1,t2; 
    public A(T t1, T t2) {
        this.t1 = t1;
        this.t2 = t2;

    public T getT1() {
        return t1;

    public T getT2() {
        return t2;

    public void setT(T t1, T t2) {
        this.t1 = t1;
        this.t2 = t2;
    public T compare(){
        if(t1.compareTo(t2) >= 0) return t1;
        else return t2;
    public String toString() {
        return ""+t1+""+t2;

2. Related tasks - Generic usage

According to the definition of generic class A, complete the test class code on the right. The definition of class a can be viewed through the folder on the right.

Test class A_ In test, the object array of the collection class ArrayList is defined to complete the operation. The input 5 logarithms are added as the elements of array in order. Then, each pair of children is output as required, and the larger of each pair of children is output.

ArrayList operation:
get(i): get the ith element.
add(i): add elements to ArrayList

Relevant knowledge

List and ArrayList are subclasses of Collection, which can store different types of data. Therefore, the data in the Collection can be represented by generics. For example:

Example 1:

Use generics:

List<T> list=new ArrayList<T>();
T t=list.get(0); 

Do not use generics:

List list=new ArrayList(); 
T t=(T)list.get(0); 

Since you can add any class object to the list, if you do not use generics, you are likely to have type conversion errors in later use.

String str1 = (String) list.get(0);
Integer value=(Integer)list.get(1);

Obviously, list.get(1) should return a reference to a String class object, so it is wrong to cast it to an Integer class.

Example 2:

Generic type used:

ArrayList <Student> array = new ArrayList();
for(int i=0;i<array.size();i++){
  Student student=array.get(i);//Cast is not required

No generics:

ArrayList  array = new ArrayList();
for(int i=0;i<array.size();i++){
 Student student=(Student)array.get(i);//Cast required

Programming requirements

Supplement the program on the right to obtain and input 5 groups of data, compare the size of each group of data, output large ones, and output 5 groups of data.

It is required to use ArrayList in combination with generic class A to compare a pair of input data, such as: (3, a),(6,5.388), and output the larger one according to the rule that the string is larger than the size. Data types can be different. According to the rule of character size ratio, a-z, the first one is smaller and the last one is larger. More than two, first than the first, and then the second. For example: a < B, AA < AB, ABC < abd

Start your mission. I wish you success!

Answer code

package step1;
import java.util.*;
public class A_Test {
	public static void main(String args[]){
		Scanner scan=new Scanner(System.in);
		ArrayList<A> array=new ArrayList<A>();
		String s1,s2;
		for(int i=0;i<5;i++){
		s1 = scan.next();
		s2 = scan.next();
		array.add(new A<String>(s1, s2));
        for (A num:
             array) {
            System.out.println(num.toString()+ ": "+num.compare()+" is bigger");

Tags: Java educoder

Posted on Mon, 01 Nov 2021 07:50:01 -0400 by azeem123456