Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList with multiple Generic types?

I have this bugging problem I cannot figure out. I have this exercise:

Complete the following generic Pair class, so that execution of the program gives the indicated output. Do not change main.

class Pair ... {   ...  }

 class GenericPairTest {        
 public static void main(String[] args) {       
    Pair<String,Integer> phoneNumber = new Pair<>("Bill's number", 1324);   
        System.out.println(phoneNumber);

           Pair<Double,Double> point = new Pair<>(3.14, 2.32);      
       System.out.println(point);   
     } 
 }

The output is suposed to be like that:

Bill's number 1324

3.14 2.32`

I tried doing this:

import java.util.*;

class Pair <T,U> {

    ArrayList<T,U> newList = new ArrayList<>();

  Pair(T inT, U inU){
    newList.add(inT,inU);
  }

}

class GenericPairTest {

    public static void main(String[] args) {        
        Pair<String,Integer> phoneNumber = 
            new Pair<>("Bill's number", 1324);  
        System.out.println(phoneNumber);
        Pair<Double,Double> point = 
            new Pair<>(3.14, 2.32);
        System.out.println(point);
    }
}

But it doesn't work :(

like image 462
Chris Dobkowski Avatar asked Feb 18 '26 14:02

Chris Dobkowski


1 Answers

Why do you need a list? You just need to store the two objects:

class Pair <T,U> {
    private T _t;
    private U _u;

    public Pair(T t, U u) {
        _t = t;
        _u = u;

    public String toString() {
        return _t + " " + _u;
    }
}
like image 141
Raffaele Rossi Avatar answered Feb 21 '26 03:02

Raffaele Rossi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!